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/policies/product_duplicates/link_policy_spec.rb | spec/policies/product_duplicates/link_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductDuplicates::LinkPolicy do
subject { described_class }
let(:accountant_for_seller) { create(:user) }
let(:admin_for_seller) { create(:user) }
let(:marketing_for_seller) { create(:user) }
let(:support_for_seller) { create(:user) }
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
before do
create(:team_membership, user: accountant_for_seller, seller:, role: TeamMembership::ROLE_ACCOUNTANT)
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING)
create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT)
end
permissions :create?, :show? do
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "denies access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).to_not permit(seller_context, product)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "denies access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/policies/products/collabs_policy_spec.rb | spec/policies/products/collabs_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Products::CollabsPolicy do
subject { described_class }
let(:accountant_for_seller) { create(:user) }
let(:admin_for_seller) { create(:user) }
let(:marketing_for_seller) { create(:user) }
let(:support_for_seller) { create(:user) }
let(:seller) { create(:named_seller) }
before do
create(:team_membership, user: accountant_for_seller, seller:, role: TeamMembership::ROLE_ACCOUNTANT)
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING)
create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT)
end
permissions :index?, :products_paged?, :memberships_paged? do
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, :collabs)
end
it "grants access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).to permit(seller_context, :collabs)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, :collabs)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, :collabs)
end
it "grants access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).to permit(seller_context, :collabs)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/policies/products/affiliated_policy_spec.rb | spec/policies/products/affiliated_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Products::AffiliatedPolicy do
subject { described_class }
let(:accountant_for_seller) { create(:user) }
let(:admin_for_seller) { create(:user) }
let(:marketing_for_seller) { create(:user) }
let(:support_for_seller) { create(:user) }
let(:seller) { create(:named_seller) }
before do
create(:team_membership, user: accountant_for_seller, seller:, role: TeamMembership::ROLE_ACCOUNTANT)
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING)
create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT)
end
permissions :index? do
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, :affiliated)
end
it "grants access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).to permit(seller_context, :affiliated)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, :affiliated)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, :affiliated)
end
it "grants access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).to permit(seller_context, :affiliated)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/policies/products/variants/link_policy_spec.rb | spec/policies/products/variants/link_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Products::Variants::LinkPolicy do
subject { described_class }
let(:accountant_for_seller) { create(:user) }
let(:admin_for_seller) { create(:user) }
let(:marketing_for_seller) { create(:user) }
let(:support_for_seller) { create(:user) }
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
before do
create(:team_membership, user: accountant_for_seller, seller:, role: TeamMembership::ROLE_ACCOUNTANT)
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING)
create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT)
end
permissions :index? do
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/policies/products/archived/link_policy_spec.rb | spec/policies/products/archived/link_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Products::Archived::LinkPolicy do
subject { described_class }
let(:accountant_for_seller) { create(:user) }
let(:admin_for_seller) { create(:user) }
let(:marketing_for_seller) { create(:user) }
let(:support_for_seller) { create(:user) }
let(:seller) { create(:named_seller) }
before do
create(:team_membership, user: accountant_for_seller, seller:, role: TeamMembership::ROLE_ACCOUNTANT)
create(:team_membership, user: admin_for_seller, seller:, role: TeamMembership::ROLE_ADMIN)
create(:team_membership, user: marketing_for_seller, seller:, role: TeamMembership::ROLE_MARKETING)
create(:team_membership, user: support_for_seller, seller:, role: TeamMembership::ROLE_SUPPORT)
end
permissions :index? do
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, :archived)
end
it "grants access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).to permit(seller_context, :archived)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, :archived)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, :archived)
end
it "grants access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).to permit(seller_context, :archived)
end
end
permissions :create? do
let(:product) { create(:product, user: seller, archived: false) }
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, product)
end
context "when product is archived" do
before do
product.update(archived: true)
end
it "denies access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
end
it "denies access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "denies access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
end
permissions :destroy? do
let(:product) { create(:product, user: seller, archived: true) }
it "grants access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).to permit(seller_context, product)
end
context "when product is not archived" do
before do
product.update!(archived: false)
end
it "denies access to owner" do
seller_context = SellerContext.new(user: seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
end
it "denies access to accountant" do
seller_context = SellerContext.new(user: accountant_for_seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
it "grants access to admin" do
seller_context = SellerContext.new(user: admin_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "grants access to marketing" do
seller_context = SellerContext.new(user: marketing_for_seller, seller:)
expect(subject).to permit(seller_context, product)
end
it "denies access to support" do
seller_context = SellerContext.new(user: support_for_seller, seller:)
expect(subject).not_to permit(seller_context, product)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/policies/gumroad_blog/posts_policy_spec.rb | spec/policies/gumroad_blog/posts_policy_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/policy_examples"
describe GumroadBlog::PostsPolicy do
subject { described_class }
let(:seller) { create(:user) }
let(:another_seller) { create(:user) }
let(:admin_for_seller) do
create(
:team_membership,
seller: seller,
role: TeamMembership::ROLE_ADMIN,
).user
end
let(:accountant_for_seller) do
create(
:team_membership,
seller: seller,
role: TeamMembership::ROLE_ACCOUNTANT,
).user
end
let(:marketing_for_seller) do
create(
:team_membership,
seller: seller,
role: TeamMembership::ROLE_MARKETING,
).user
end
let(:support_for_seller) do
create(
:team_membership,
seller: seller,
role: TeamMembership::ROLE_SUPPORT,
).user
end
let(:published_post) do
create(
:audience_post,
:published,
seller: seller,
deleted_at: nil,
shown_on_profile: true,
workflow_id: nil
)
end
let(:unpublished_post) do
create(
:audience_post,
seller: seller,
published_at: nil,
deleted_at: nil,
shown_on_profile: true,
workflow_id: nil
)
end
let(:dead_post) do
create(
:audience_post,
:published,
seller: seller,
deleted_at: Time.current,
shown_on_profile: true,
workflow_id: nil
)
end
let(:hidden_post) do
create(
:audience_post,
:published,
seller: seller,
deleted_at: nil,
shown_on_profile: false,
workflow_id: nil
)
end
let(:workflow_post) do
create(
:audience_post,
:published,
seller: seller,
deleted_at: nil,
shown_on_profile: true,
workflow_id: "some_workflow_id"
)
end
let(:no_audience_post) do
create(
:post,
:published,
seller: seller,
deleted_at: nil,
shown_on_profile: true,
workflow_id: nil
)
end
let(:another_seller_post) do
create(
:audience_post,
:published,
seller: another_seller,
deleted_at: nil,
shown_on_profile: true,
workflow_id: nil
)
end
let(:context_seller) { seller }
permissions :index? do
let(:record) { published_post }
it_behaves_like "an access-granting policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "grants access to anonymous users" do
expect(subject).to permit(SellerContext.logged_out, record)
end
end
permissions :show? do
context "when the post is published and meets all criteria" do
let(:record) { published_post }
it_behaves_like "an access-granting policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "grants access to anonymous users" do
expect(subject).to permit(SellerContext.logged_out, record)
end
end
context "when the post is unpublished" do
let(:record) { unpublished_post }
it_behaves_like "an access-granting policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
context "for another seller" do
let(:context_seller) { another_seller }
it_behaves_like "an access-denying policy for roles", [
:another_seller,
]
end
it "denies access to anonymous users" do
expect(subject).not_to permit(SellerContext.logged_out, record)
end
end
context "when the post is not alive" do
let(:record) { dead_post }
it_behaves_like "an access-denying policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "denies access to anonymous users" do
expect(subject).not_to permit(SellerContext.logged_out, record)
end
end
context "when the post is not shown on profile" do
let(:record) { hidden_post }
it_behaves_like "an access-denying policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "denies access to anonymous users" do
expect(subject).not_to permit(SellerContext.logged_out, record)
end
end
context "when the post is a workflow post" do
let(:record) { workflow_post }
it_behaves_like "an access-denying policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "denies access to anonymous users" do
expect(subject).not_to permit(SellerContext.logged_out, record)
end
end
context "when the post is not an audience post" do
let(:record) { no_audience_post }
it_behaves_like "an access-denying policy for roles", [
:seller,
:admin_for_seller,
:accountant_for_seller,
:marketing_for_seller,
:support_for_seller,
]
it "denies access to anonymous users" do
expect(subject).not_to permit(SellerContext.logged_out, record)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/validators/email_format_validator_spec.rb | spec/validators/email_format_validator_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe EmailFormatValidator do
let(:model_class) do
Class.new do
include ActiveModel::Model
attr_accessor :email
end
end
let(:model) { model_class.new }
let(:valid_value) { "user@example.com" }
let(:invalid_value) { "invalid" }
before { model_class.clear_validators! }
it "does not accept blank or nil values by default" do
model_class.validates :email, email_format: true
model.email = nil
expect(model).not_to be_valid
model.email = ""
expect(model).not_to be_valid
end
it "accepts valid emails" do
model_class.validates :email, email_format: true
model.email = valid_value
expect(model).to be_valid
model.email = "user@example.com"
expect(model).to be_valid
end
it "accepts nil with allow_nil option" do
model_class.validates :email, email_format: true, allow_nil: true
model.email = nil
expect(model).to be_valid
model.email = ""
expect(model).not_to be_valid
end
it "accepts blank values with allow_blank option" do
model_class.validates :email, email_format: true, allow_blank: true
model.email = ""
expect(model).to be_valid
model.email = " "
expect(model).to be_valid
model.email = nil
expect(model).to be_valid
end
describe ".valid?" do
it "returns true for valid emails" do
expect(EmailFormatValidator.valid?(valid_value)).to be true
end
it "returns false for invalid emails and blank values" do
expect(EmailFormatValidator.valid?(invalid_value)).to be false
expect(EmailFormatValidator.valid?(nil)).to be false
expect(EmailFormatValidator.valid?("")).to be false
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/validators/not_reserved_email_domain_validator_spec.rb | spec/validators/not_reserved_email_domain_validator_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe NotReservedEmailDomainValidator do
let(:model_class) do
Class.new do
include ActiveModel::Model
attr_accessor :email
end
end
let(:model) { model_class.new }
before { model_class.clear_validators! }
it "validates the email domain in case-insensitive manner" do
model_class.validates :email, not_reserved_email_domain: true
model.email = "user@GumRoad.com"
expect(model).not_to be_valid
model.email = "user@GumRoad.org"
expect(model).not_to be_valid
model.email = "user@GumRoad.dev"
expect(model).not_to be_valid
model.email = "user@gmail.com"
expect(model).to be_valid
end
describe ".domain_reserved?" do
it "validates the email domain in case-insensitive manner" do
expect(described_class.domain_reserved?("user@gumroad.com")).to be true
expect(described_class.domain_reserved?("user@GumRoad.com")).to be true
expect(described_class.domain_reserved?("user@GumRoad.org")).to be true
expect(described_class.domain_reserved?("user@GumRoad.dev")).to be true
expect(described_class.domain_reserved?("user@gmail.com")).to be false
expect(described_class.domain_reserved?(nil)).to be false
expect(described_class.domain_reserved?("")).to be false
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/validators/isbn_validator_spec.rb | spec/validators/isbn_validator_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe IsbnValidator do
let(:model_class) do
Class.new do
include ActiveModel::Model
attr_accessor :isbn
end
end
let(:model) { model_class.new }
before { model_class.clear_validators! }
context "when ISBN-13" do
let(:valid_value) { Faker::Code.isbn(base: 13) }
let(:valid_value_digits) { valid_value.gsub(/[^0-9]/, "") }
let(:invalid_value) { "978-3-16-148410-X" }
it "accepts valid isbns" do
model_class.validates :isbn, isbn: true
model.isbn = valid_value
expect(model).to be_valid
end
it "rejects ISBN-13 with em dashes" do
model_class.validates :isbn, isbn: true
isbn_with_em_dashes = valid_value_digits.chars.each_slice(4).map { |s| s.join("—") }.join("—")
model.isbn = isbn_with_em_dashes
expect(model).not_to be_valid
end
it "rejects ISBN-13 with en dashes" do
model_class.validates :isbn, isbn: true
isbn_with_en_dashes = valid_value_digits.chars.each_slice(4).map { |s| s.join("–") }.join("–")
model.isbn = isbn_with_en_dashes
expect(model).not_to be_valid
end
end
context "when ISBN-10" do
let(:valid_value) { Faker::Code.isbn }
let(:invalid_value) { "0-306-40615-X" }
it "accepts valid isbns" do
model_class.validates :isbn, isbn: true
model.isbn = valid_value
expect(model).to be_valid
end
it "rejects invalid isbns" do
model_class.validates :isbn, isbn: true
model.isbn = invalid_value
expect(model).not_to be_valid
end
end
it "accepts nil with allow_nil option" do
model_class.validates :isbn, isbn: true, allow_nil: true
model.isbn = nil
expect(model).to be_valid
model.isbn = ""
expect(model).not_to be_valid
end
it "accepts blank values with allow_blank option" do
model_class.validates :isbn, isbn: true, allow_blank: true
model.isbn = ""
expect(model).to be_valid
model.isbn = " "
expect(model).to be_valid
model.isbn = nil
expect(model).to be_valid
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/moldova_bank_accounts.rb | spec/factories/moldova_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :moldova_bank_account do
association :user
bank_code { "AAAAMDMDXXX" }
account_number { "MD07AG123456789012345678" }
account_number_last_four { "5678" }
account_holder_full_name { "Chuck Bartowski" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/user_tax_forms.rb | spec/factories/user_tax_forms.rb | # frozen_string_literal: true
FactoryBot.define do
factory :user_tax_form do
user
tax_year { 2024 }
tax_form_type { "us_1099_k" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/cambodia_bank_accounts.rb | spec/factories/cambodia_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :cambodia_bank_account do
user
bank_code { "AAAAKHKHXXX" }
account_number { "000123456789" }
account_number_last_four { "6789" }
account_holder_full_name { "Cambodian Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/product_installment_plans.rb | spec/factories/product_installment_plans.rb | # frozen_string_literal: true
FactoryBot.define do
factory :product_installment_plan do
link { create(:product, price_cents: 1000, native_type: Link::NATIVE_TYPE_DIGITAL) }
number_of_installments { 3 }
recurrence { "monthly" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/sri_lanka_bank_accounts.rb | spec/factories/sri_lanka_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :sri_lanka_bank_account do
user
bank_code { "AAAALKLXXXX" }
branch_code { "7010999" }
account_number { "0000012345" }
account_number_last_four { "2345" }
account_holder_full_name { "Sri Lankan Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/community_chat_messages.rb | spec/factories/community_chat_messages.rb | # frozen_string_literal: true
FactoryBot.define do
factory :community_chat_message do
association :community
association :user
content { "Hello, community!" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/utm_link_visits.rb | spec/factories/utm_link_visits.rb | # frozen_string_literal: true
FactoryBot.define do
factory :utm_link_visit do
association :utm_link
user { nil }
ip_address { "127.0.0.1" }
browser_guid { SecureRandom.uuid }
country_code { "US" }
referrer { "https://twitter.com" }
user_agent { "Mozilla/5.0" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/mauritius_bank_accounts.rb | spec/factories/mauritius_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :mauritius_bank_account do
user
account_number { "MU17BOMM0101101030300200000MUR" }
account_number_last_four { "0MUR" }
bank_code { "AAAAMUMUXYZ" }
account_holder_full_name { "John Doe" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/el_salvador_bank_accounts.rb | spec/factories/el_salvador_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :el_salvador_bank_account do
association :user
bank_number { "AAAASVS1XXX" }
account_number { "SV44BCIE12345678901234567890" }
account_number_last_four { "7890" }
account_holder_full_name { "Chuck Bartowski" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/bolivia_bank_accounts.rb | spec/factories/bolivia_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :bolivia_bank_account do
user
account_number { "000123456789" }
bank_code { "040" }
account_number_last_four { "6789" }
account_holder_full_name { "Chuck Bartowski" }
state { "unverified" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/uruguay_bank_accounts.rb | spec/factories/uruguay_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :uruguay_bank_account do
user
account_number { "000123456789" }
account_number_last_four { "6789" }
bank_code { "999" }
account_holder_full_name { "John Doe" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/jamaica_bank_accounts.rb | spec/factories/jamaica_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :jamaica_bank_account do
user
bank_code { "111" } # 3-digit bank code
branch_code { "00000" } # 5-digit branch code
account_number { "000123456789" } # 1-18 digit account number
account_number_last_four { "6789" }
account_holder_full_name { "John Doe" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/dominican_republic_bank_accounts.rb | spec/factories/dominican_republic_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :dominican_republic_bank_account do
user
account_number { "000123456789" }
bank_code { "999" }
account_number_last_four { "6789" }
account_holder_full_name { "Chuck Bartowski" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/community_chat_recaps.rb | spec/factories/community_chat_recaps.rb | # frozen_string_literal: true
FactoryBot.define do
factory :community_chat_recap do
association :community_chat_recap_run
association :community
association :seller, factory: :user
summarized_message_count { 10 }
input_token_count { 1000 }
output_token_count { 200 }
status { "pending" }
trait :finished do
status { "finished" }
end
trait :failed do
status { "failed" }
end
trait :without_community do
community { nil }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/communities.rb | spec/factories/communities.rb | # frozen_string_literal: true
FactoryBot.define do
factory :community do
association :seller, factory: :user
resource { association :product }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/utm_link_driven_sales.rb | spec/factories/utm_link_driven_sales.rb | # frozen_string_literal: true
FactoryBot.define do
factory :utm_link_driven_sale do
association :utm_link
association :utm_link_visit
association :purchase
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/community_chat_recap_runs.rb | spec/factories/community_chat_recap_runs.rb | # frozen_string_literal: true
FactoryBot.define do
factory :community_chat_recap_run do
recap_frequency { "daily" }
from_date { (Time.current - rand(1..1000).days).beginning_of_day }
to_date { (Time.current - rand(1..1000).days).end_of_day }
recaps_count { 0 }
trait :weekly do
recap_frequency { "weekly" }
from_date { (Date.yesterday - 6.days).beginning_of_day }
to_date { Date.yesterday.end_of_day }
end
trait :finished do
finished_at { Time.current }
end
trait :notified do
notified_at { Time.current }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/armenia_bank_accounts.rb | spec/factories/armenia_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :armenia_bank_account do
user
bank_code { "AAAAAMNNXXX" }
account_number { "00001234567" }
account_number_last_four { "4567" }
account_holder_full_name { "Armenia creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/benin_bank_accounts.rb | spec/factories/benin_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :benin_bank_account do
user
account_number { "BJ66BJ0610100100144390000769" }
account_number_last_four { "0769" }
account_holder_full_name { "Benin Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/macao_bank_accounts.rb | spec/factories/macao_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :macao_bank_account do
user
account_number { "0000000001234567897" }
account_number_last_four { "7897" }
bank_code { "AAAAMOMXXXX" }
account_holder_full_name { "Macao Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/public_files.rb | spec/factories/public_files.rb | # frozen_string_literal: true
FactoryBot.define do
factory :public_file do
sequence(:original_file_name) { |n| "test-#{n}.mp3" }
sequence(:display_name) { |n| "Test audio #{n}" }
public_id { PublicFile.generate_public_id }
resource { association :product }
trait :with_audio do
after(:build) do |public_file|
public_file.file.attach(
io: File.open(Rails.root.join("spec/support/fixtures/test.mp3")),
filename: "test.mp3",
content_type: "audio/mpeg"
)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/kuwait_bank_accounts.rb | spec/factories/kuwait_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :kuwait_bank_account do
user
bank_code { "AAAAKWKWXYZ" }
account_number { "KW81CBKU0000000000001234560101" }
account_number_last_four { "0101" }
account_holder_full_name { "Kuwaiti Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/last_read_community_chat_messages.rb | spec/factories/last_read_community_chat_messages.rb | # frozen_string_literal: true
FactoryBot.define do
factory :last_read_community_chat_message do
association :user
association :community
association :community_chat_message
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/utm_links.rb | spec/factories/utm_links.rb | # frozen_string_literal: true
FactoryBot.define do
factory :utm_link do
association :seller, factory: :user
sequence(:title) { |n| "UTM Link #{n}" }
target_resource_type { :profile_page }
sequence(:utm_campaign) { |n| "summer-sale-#{n}" }
utm_medium { "social" }
utm_source { "twitter" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/cote_d_ivoire_bank_accounts.rb | spec/factories/cote_d_ivoire_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :cote_d_ivoire_bank_account do
user
account_number { "CI93CI0080111301134291200589" }
account_number_last_four { "0589" }
account_holder_full_name { "Cote d'Ivoire Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/panama_bank_accounts.rb | spec/factories/panama_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :panama_bank_account do
association :user
bank_number { "AAAAPAPAXXX" }
account_number { "000123456789" }
account_number_last_four { "6789" }
account_holder_full_name { "Chuck Bartowski" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/uzbekistan_bank_accounts.rb | spec/factories/uzbekistan_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :uzbekistan_bank_account do
user
account_number { "99934500012345670024" }
bank_code { "AAAAUZUZXXX" }
branch_code { "00000" }
account_number_last_four { "0024" }
account_holder_full_name { "Chuck Bartowski" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/mongolia_bank_accounts.rb | spec/factories/mongolia_bank_accounts.rb | # frozen_string_literal: true
FactoryBot.define do
factory :mongolia_bank_account do
user
bank_code { "AAAAMNUBXXX" }
account_number { "0002222001" }
account_number_last_four { "2001" }
account_holder_full_name { "Mongolian Creator" }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/factories/community_notification_settings.rb | spec/factories/community_notification_settings.rb | # frozen_string_literal: true
FactoryBot.define do
factory :community_notification_setting do
association :user
association :seller, factory: :user
recap_frequency { "daily" }
trait :weekly_recap do
recap_frequency { "weekly" }
end
trait :no_recap do
recap_frequency { nil }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/third_party_analytics_controller_spec.rb | spec/controllers/third_party_analytics_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ThirdPartyAnalyticsController do
render_views
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@purchase = create(:purchase, link: @product)
@product_product_snippet = create(:third_party_analytic, user: @seller, link: @product, location: "product", analytics_code: "product product")
@product_user_snippet = create(:third_party_analytic, user: @seller, link: nil, location: "product", analytics_code: "product user")
@receipt_product_snippet = create(:third_party_analytic, user: @seller, link: @product, location: "receipt", analytics_code: "receipt product")
@receipt_user_snippet = create(:third_party_analytic, user: @seller, link: nil, location: "receipt", analytics_code: "receipt user")
@global_product_snippet = create(:third_party_analytic, user: @seller, link: @product, location: "all", analytics_code: "global product")
@global_user_snippet = create(:third_party_analytic, user: @seller, link: nil, location: "all", analytics_code: "global user")
end
describe "index" do
context "when location is product" do
it "includes all applicable snippets" do
get :index, params: { link_id: @product.unique_permalink, location: "product" }
expect(response.body).to include @product_product_snippet.analytics_code
expect(response.body).to include @product_user_snippet.analytics_code
expect(response.body).to include @global_user_snippet.analytics_code
expect(response.body).to include @global_product_snippet.analytics_code
expect(response.body).to_not include @receipt_user_snippet.analytics_code
expect(response.body).to_not include @receipt_product_snippet.analytics_code
end
end
context "when location is receipt" do
it "includes all applicable snippets" do
get :index, params: { link_id: @product.unique_permalink, purchase_id: @purchase.external_id, location: "receipt" }
expect(response.body).to include @receipt_user_snippet.analytics_code
expect(response.body).to include @receipt_product_snippet.analytics_code
expect(response.body).to include @global_user_snippet.analytics_code
expect(response.body).to include @global_product_snippet.analytics_code
expect(response.body).to_not include @product_product_snippet.analytics_code
expect(response.body).to_not include @product_user_snippet.analytics_code
end
end
it "successfully returns replaced analytics code" do
@global_product_snippet.update_attribute(:analytics_code, "<img height='$VALUE' width='$CURRENCY' alt='' style='display:none' src='http://placehold.it/150x150' />")
get :index, params: { link_id: @product.unique_permalink, purchase_id: @purchase.external_id, location: "receipt" }
expect(response.body).to include "<img height='1' width='USD' alt='' style='display:none' src='http://placehold.it/150x150' />"
end
it "successfully returns analytics code with order id" do
@global_product_snippet.update_attribute(:analytics_code, "<img height='$ORDER' width='$CURRENCY' alt='' style='display:none' src='http://placehold.it/150x150' />")
get :index, params: { link_id: @product.unique_permalink, purchase_id: @purchase.external_id, location: "receipt" }
expect(response.body).to include "<img height='#{@purchase.external_id}' width='USD' alt='' style='display:none' src='http://placehold.it/150x150' />"
end
it "doesn't return any analytics code if none exist for product or user" do
new_product = create(:product)
new_purchase = create(:purchase, link: new_product)
get :index, params: { link_id: new_product.unique_permalink, purchase_id: new_purchase.external_id }
expect(response.body).to_not include @product_product_snippet.analytics_code
expect(response.body).to_not include @product_user_snippet.analytics_code
expect(response.body).to_not include @global_user_snippet.analytics_code
expect(response.body).to_not include @global_product_snippet.analytics_code
expect(response.body).to_not include @receipt_user_snippet.analytics_code
expect(response.body).to_not include @receipt_product_snippet.analytics_code
end
it "raises an e404 if the purchase does not belong to the product" do
purchase = create(:purchase, link: create(:product))
expect { get :index, params: { link_id: @product.unique_permalink, purchase_id: purchase.external_id } }.to raise_error(ActionController::RoutingError)
end
it "raises an e404 if the purchase does not exist" do
expect { get :index, params: { link_id: @product.unique_permalink, purchase_id: "@purchase.external_id" } }.to raise_error(ActionController::RoutingError)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/checkout_controller_spec.rb | spec/controllers/checkout_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe CheckoutController do
describe "GET index" do
it "returns HTTP success and assigns correct instance variables" do
get :index
expect(assigns[:hide_layouts]).to eq(true)
expect(assigns[:on_checkout_page]).to eq(true)
expect(response).to be_successful
end
describe "process_cart_id_param check" do
let(:user) { create(:user) }
let(:cart) { create(:cart, user:) }
context "when user is logged in" do
before do
sign_in user
end
it "does not redirect when cart_id is blank" do
get :index
expect(response).to be_successful
end
it "redirects to the same path removing the `cart_id` query param" do
get :index, params: { cart_id: create(:cart, :guest).external_id }
expect(response).to redirect_to(checkout_index_path(referrer: UrlService.discover_domain_with_protocol))
end
end
context "when user is not logged in" do
it "does not redirect when `cart_id` is blank" do
get :index
expect(response).to be_successful
end
it "redirects to the same path when `cart_id` is not found" do
get :index, params: { cart_id: "no-such-cart" }
expect(response).to redirect_to(checkout_index_path(referrer: UrlService.discover_domain_with_protocol))
end
it "redirects to the same path when the cart for `cart_id` is deleted" do
cart.mark_deleted!
get :index, params: { cart_id: cart.external_id }
expect(response).to redirect_to(checkout_index_path(referrer: UrlService.discover_domain_with_protocol))
end
context "when the cart matching the `cart_id` query param belongs to a user" do
it "redirects to the login page path with `next` param set to the checkout path" do
get :index, params: { cart_id: cart.external_id }
expect(response).to redirect_to(login_url(next: checkout_index_path(referrer: UrlService.discover_domain_with_protocol), email: cart.user.email))
end
end
context "when the cart matching the `cart_id` query param has the `browser_guid` same as the current `_gumroad_guid` cookie value" do
it "redirects to the same path without modifying the cart" do
browser_guid = SecureRandom.uuid
cookies[:_gumroad_guid] = browser_guid
cart = create(:cart, :guest, browser_guid:)
expect do
expect do
get :index, params: { cart_id: cart.external_id }
end.not_to change { Cart.alive.count }
end.not_to change { cart.reload }
expect(response).to redirect_to(checkout_index_path(referrer: UrlService.discover_domain_with_protocol))
end
end
context "when the cart matching the `cart_id` query param has the `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 and redirects to the same path removing the `cart_id` query param" do
product1 = create(:product)
product2 = create(:product)
cart = create(:cart, :guest, browser_guid: SecureRandom.uuid)
create(:cart_product, cart:, product: product1)
browser_guid = SecureRandom.uuid
cookies[:_gumroad_guid] = browser_guid
current_guest_cart = create(:cart, :guest, browser_guid:, email: "john@example.com")
create(:cart_product, cart: current_guest_cart, product: product2)
expect do
get :index, params: { cart_id: cart.external_id }
end.to change { Cart.alive.count }.from(2).to(1)
expect(response).to redirect_to(checkout_index_path(referrer: UrlService.discover_domain_with_protocol))
expect(Cart.alive.sole.id).to eq(cart.id)
expect(current_guest_cart.reload).to be_deleted
expect(cart.reload.email).to eq("john@example.com")
expect(cart.alive_cart_products.pluck(:product_id)).to match_array([product1.id, product2.id])
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/controllers/profile_sections_controller_spec.rb | spec/controllers/profile_sections_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe ProfileSectionsController do
let(:seller) { create(:named_seller) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
it_behaves_like "authorize called for controller" do
let(:record) { :profile_section }
let(:request_params) { { id: "id" } }
end
include_context "with user signed in as admin for seller"
describe "POST create" do
it "creates a product section" do
products = create_list(:product, 2)
expect do
post :create, params: {
type: "SellerProfileProductsSection",
header: "Hello",
hide_header: true,
show_filters: false,
shown_products: products.map(&:external_id),
default_product_sort: "page_layout",
add_new_products: true,
}, as: :json
end.to change { seller.seller_profile_products_sections.count }.from(0).to(1)
section = seller.seller_profile_products_sections.sole
expect(section).to have_attributes(
type: "SellerProfileProductsSection",
header: "Hello",
hide_header: true,
show_filters: false,
shown_products: products.map(&:id),
default_product_sort: "page_layout",
add_new_products: true,
product_id: nil
)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a posts section" do
create(:installment, :published, installment_type: Installment::FOLLOWER_TYPE, seller:, shown_on_profile: true)
create(:installment, :published, installment_type: Installment::AUDIENCE_TYPE, seller:)
posts = create_list(:published_installment, 2, installment_type: Installment::AUDIENCE_TYPE, seller:, shown_on_profile: true)
expect do
post :create, params: {
type: "SellerProfilePostsSection", header: "Hello", hide_header: true, shown_posts: posts.map(&:external_id)
}, as: :json
end.to change { seller.seller_profile_posts_sections.count }.from(0).to(1)
section = seller.seller_profile_posts_sections.reload.sole
expect(section).to have_attributes(
type: "SellerProfilePostsSection",
header: "Hello",
hide_header: true,
shown_posts: posts.map(&:id),
product_id: nil
)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a featured product section" do
product = create(:product, name: "Special product", user: seller)
expect do
post :create, params: {
type: "SellerProfileFeaturedProductSection", header: "My amazing product", hide_header: false, featured_product_id: product.external_id,
}, as: :json
end.to change { seller.seller_profile_featured_product_sections.count }.from(0).to(1)
section = seller.seller_profile_sections.reload.sole
expect(section).to have_attributes(
type: "SellerProfileFeaturedProductSection",
header: "My amazing product",
hide_header: false,
featured_product_id: product.id,
product_id: nil
)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a subscribe section" do
expect do
post :create, params: {
type: "SellerProfileSubscribeSection", header: "Subscribe to me!", hide_header: false, button_label: ""
}, as: :json
end.to change { seller.seller_profile_subscribe_sections.count }.from(0).to(1)
section = seller.seller_profile_subscribe_sections.reload.sole
expect(section).to have_attributes(
type: "SellerProfileSubscribeSection",
header: "Subscribe to me!",
hide_header: false,
button_label: "",
product_id: nil,
)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a rich text section" do
params = {
type: "SellerProfileRichTextSection",
header: "Hello",
hide_header: true,
text: { "content" => nil, "anything_can_be_here" => "we don't validate this" }
}
expect do
post :create, params: params, as: :json
end.to change { seller.seller_profile_rich_text_sections.count }.from(0).to(1)
section = seller.seller_profile_rich_text_sections.reload.sole
expect(section).to have_attributes(params)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a section for a product" do
product = create(:product, user: seller)
params = {
type: "SellerProfileFeaturedProductSection", product_id: product.external_id
}
expect do
post :create, params:, as: :json
end.to change { seller.seller_profile_featured_product_sections.count }.from(0).to(1)
section = seller.seller_profile_sections.reload.sole
expect(section.product).to eq product
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "creates a wishlists section" do
wishlist = create(:wishlist, user: seller)
expect do
post :create, params: {
type: "SellerProfileWishlistsSection", header: "Hello", hide_header: false, shown_wishlists: [wishlist.external_id]
}, as: :json
end.to change { seller.seller_profile_wishlists_sections.count }.from(0).to(1)
section = seller.seller_profile_wishlists_sections.reload.sole
expect(section).to have_attributes(
type: "SellerProfileWishlistsSection",
header: "Hello",
hide_header: false,
shown_wishlists: [wishlist.id],
)
expect(response).to be_successful
expect(response.parsed_body).to eq({ "id" => section.external_id })
end
it "returns an error for invalid types" do
post :create, params: {
type: "SellerProfileFakeSection", header: "Hello", hide_header: true, show_filters: false
}, as: :json
expect(response).to have_http_status :unprocessable_content
expect(response.parsed_body).to eq({ "error" => "Invalid section type" })
end
it "returns an error for invalid data" do
post :create, params: {
type: "SellerProfileProductsSection", show_filters: "i hack u :)"
}, as: :json
expect(response).to have_http_status :unprocessable_content
expect(response.parsed_body["error"]).to include("The property '#/show_filters' of type string did not match the following type: boolean")
end
end
describe "PATCH update" do
let(:section) { create(:seller_profile_products_section, seller:, header: "A!", shown_products: [1], hide_header: true) }
it "updates the profile section" do
products = create_list(:product, 2)
patch :update, params: {
id: section.external_id, header: "B!", shown_products: products.map(&:external_id)
}, as: :json
expect(section.reload).to have_attributes({
header: "B!",
shown_products: products.map(&:id),
hide_header: true
})
expect(response).to be_successful
end
it "disallows changing the shown_posts of a posts section" do
post1 = create(:published_installment, installment_type: Installment::AUDIENCE_TYPE, seller:, shown_on_profile: true)
post2 = create(:published_installment, installment_type: Installment::AUDIENCE_TYPE, seller:, shown_on_profile: true)
section = create(:seller_profile_posts_section, seller:, shown_posts: [post1.id])
patch :update, params: {
id: section.external_id, header: "B!", shown_posts: [post1.external_id, post2.external_id]
}, as: :json
expect(section.reload).to have_attributes({ header: "B!", shown_posts: [post1.id] })
expect(response).to be_successful
end
it "throws a 404 error if the section does not exist" do
expect do
patch :update, params: { id: "no", header: "B!" }, as: :json
end.to raise_error ActiveRecord::RecordNotFound
end
it "throws a 404 error if the section does not belong to the seller" do
expect do
patch :update, params: { id: create(:seller_profile_products_section).external_id, header: "B!" }, as: :json
end.to raise_error ActiveRecord::RecordNotFound
end
it "disallows changing the type" do
patch :update, params: {
id: section.external_id, type: "SellerProfileFakeSection"
}, as: :json
expect(section.reload.type).to eq "SellerProfileProductsSection"
end
it "disallows changing the product id" do
patch :update, params: {
id: section.external_id, product_id: create(:product).external_id
}, as: :json
expect(section.reload.product_id).to be_nil
end
it "returns an error for invalid data" do
patch :update, params: { id: section.external_id, show_filters: "i hack u :)" }, as: :json
expect(response).to have_http_status :unprocessable_content
expect(response.parsed_body).to eq({ "error" => "The property '#/show_filters' of type string did not match the following type: boolean" })
end
context "rich content" do
let(:product) { create(:product, user: seller) }
let(:upsell) { create(:upsell, seller: seller, product: product, is_content_upsell: true) }
let(:section) do
create(
:seller_profile_rich_text_section,
seller: seller,
header: "Hello",
text: {
"type" => "doc",
"content" => [
{ "type" => "paragraph", "content" => [{ "text" => "hi", "type" => "text" }] },
{ "type" => "upsellCard", "attrs" => { "discount" => nil, "id" => upsell.external_id, "productId" => product.external_id } }
]
}
)
end
let(:new_text) do
{
"type" => "doc",
"content" => [
{ "type" => "paragraph", "content" => [{ "text" => "hi", "type" => "text" }] },
{ "type" => "upsellCard", "attrs" => { "discount" => nil, "productId" => product.external_id } }
]
}
end
it "invokes SaveContentUpsellsService" do
expect(SaveContentUpsellsService).to receive(:new).with(
seller: seller,
content: new_text["content"].map { |node| ActionController::Parameters.new(node).permit! },
old_content: section.text["content"]
).and_call_original
patch :update, params: { id: section.external_id, text: new_text }, as: :json
expect(response).to be_successful
expect(upsell.reload).to be_deleted
new_upsell = Upsell.last
expect(section.reload.text["content"][1]["attrs"]["id"]).to eq(new_upsell.external_id)
expect(new_upsell).to be_alive
expect(new_upsell.product_id).to eq(product.id)
end
end
end
describe "DELETE destroy" do
it "deletes the profile section" do
create(:seller_profile_products_section, seller:)
section = create(:seller_profile_products_section, seller:)
expect do
delete :destroy, params: { id: section.external_id }, as: :json
end.to change { seller.seller_profile_sections.count }.from(2).to(1)
expect(response).to be_successful
end
it "throws a 404 error if the section does not exist" do
expect do
delete :destroy, params: { id: "no" }, as: :json
end.to raise_error ActiveRecord::RecordNotFound
end
it "throws a 404 error if the section does not belong to the seller" do
expect do
delete :destroy, params: { id: create(:seller_profile_products_section).external_id }, as: :json
end.to raise_error ActiveRecord::RecordNotFound
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/public_controller_spec.rb | spec/controllers/public_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe PublicController, type: :controller, inertia: true do
render_views
let!(:demo_product) { create(:product, unique_permalink: "demo") }
{ api: "API" }.each do |url, title|
describe "GET '#{url}'" do
it "succeeds and set instance variable" do
get(url)
expect(assigns(:title)).to eq(title)
expect(assigns(:"on_#{url}_page")).to be(true)
end
end
end
describe "GET ping", inertia: true do
it "succeeds and renders with Inertia" do
get :ping
expect(response).to be_successful
expect(assigns(:title)).to eq("Ping")
expect(inertia).to render_component("Public/Ping")
end
end
describe "GET home" do
context "when not authenticated" do
it "redirects to the login page" do
get :home
expect(response).to redirect_to(login_path)
end
end
context "when authenticated" do
before do
sign_in create(:user)
end
it "redirects to the dashboard page" do
get :home
expect(response).to redirect_to(dashboard_path)
end
end
end
describe "GET widgets" do
context "with user signed in as admin for seller" do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it "renders the inertia page with correct component and title" do
get :widgets
expect(response).to be_successful
expect(inertia).to render_component("Public/Widgets")
expect(assigns(:title)).to eq("Widgets")
end
end
end
describe "POST charge_data" do
it "returns correct information if no purchases match" do
get :charge_data, params: { last_4: "4242", email: "edgar@gumroad.com" }
expect(response.parsed_body["success"]).to be(false)
end
it "returns correct information if a purchase matches" do
create(:purchase, price_cents: 100, fee_cents: 30, card_visual: "**** 4242", email: "edgar@gumroad.com")
get :charge_data, params: { last_4: "4242", email: "edgar@gumroad.com" }
expect(response.parsed_body["success"]).to be(true)
end
it "returns only the successful and gift_receiver_purchase_successful purchases that match the criteria" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
purchase = create(:purchase, price_cents: 100, fee_cents: 30, card_visual: "**** 4242", email: "edgar@gumroad.com")
create(:purchase, purchase_state: "preorder_authorization_successful", price_cents: 100, fee_cents: 30, card_visual: "**** 4242", email: "edgar@gumroad.com")
gift_receiver_purchase = create(:purchase, purchase_state: "gift_receiver_purchase_successful", price_cents: 100, fee_cents: 30, card_visual: "**** 4242", email: "edgar@gumroad.com")
create(:purchase, purchase_state: "failed", price_cents: 100, fee_cents: 30, card_visual: "**** 4242", email: "edgar@gumroad.com")
expect(CustomerMailer).to receive(:grouped_receipt).with([purchase.id, gift_receiver_purchase.id]).and_return(mail_double)
get :charge_data, params: { last_4: "4242", email: "edgar@gumroad.com" }
expect(response.parsed_body["success"]).to be(true)
end
end
describe "paypal_charge_data" do
context "when there is no invoice_id value passed" do
let(:params) { { invoice_id: nil } }
it "returns false" do
get(:paypal_charge_data, params:)
expect(response.parsed_body["success"]).to be(false)
expect(SendPurchaseReceiptJob.jobs.size).to eq(0)
end
end
context "with a valid invoice_id value" do
let(:purchase) { create(:purchase, price_cents: 100, fee_cents: 30) }
let(:params) { { invoice_id: purchase.external_id } }
it "returns correct information and enqueues job for sending the receipt" do
get(:paypal_charge_data, params:)
expect(response.parsed_body["success"]).to be(true)
expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("critical")
end
context "when the product has stampable PDFs" do
before do
allow_any_instance_of(Link).to receive(:has_stampable_pdfs?).and_return(true)
end
it "enqueues job for sending the receipt on the default queue" do
get(:paypal_charge_data, params:)
expect(SendPurchaseReceiptJob).to have_enqueued_sidekiq_job(purchase.id).on("default")
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/controllers/affiliate_requests_controller_spec.rb | spec/controllers/affiliate_requests_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe AffiliateRequestsController do
describe "GET new" do
context "when the creator doesn't exist" do
it "renders 404 page" do
expect do
get :new, params: { username: "someone" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
context "when requested through the app domain" do
let(:creator) { create(:named_user) }
it "redirects to the affiliates page on subdomain" do
get :new, params: { username: creator.username }
expect(response).to redirect_to custom_domain_new_affiliate_request_url(host: creator.subdomain_with_protocol)
expect(response).to have_http_status(:moved_permanently)
end
end
context "when the creator has not enabled affiliate requests" do
let(:creator) { create(:named_user) }
let!(:product) { create(:product, user: creator) }
before do
@request.host = URI.parse(creator.subdomain_with_protocol).host
end
it "renders 404 page" do
expect do
get :new, params: { username: creator.username }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
context "when the creator has enabled affiliate requests" 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:) }
before do
@request.host = URI.parse(creator.subdomain_with_protocol).host
end
context "when the requester is not signed in" do
it "renders the affiliate request form" do
get :new, params: { username: creator.username }
expect(response).to have_http_status(:ok)
expect(response).to render_template(:new)
expect(assigns[:title]).to eq("Become an affiliate for #{creator.display_name}")
end
end
context "when the requester is signed in" do
let(:requester) { create(:named_user) }
before(:each) do
sign_in requester
end
it "renders the affiliate request form" do
get :new, params: { username: creator.username }
expect(response).to have_http_status(:ok)
expect(response).to render_template(:new)
expect(assigns[:title]).to eq("Become an affiliate for #{creator.display_name}")
end
end
context "with user signed in as admin for seller" do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it "assigns the correct instance variables and renders template" do
get :new, params: { username: creator.username }
expect(response).to be_successful
expect(response).to render_template(:new)
expect(assigns[:title]).to eq("Become an affiliate for #{creator.display_name}")
expect(assigns[:hide_layouts]).to be(true)
profile_presenter = assigns[:profile_presenter]
expect(profile_presenter.seller).to eq(creator)
expect(profile_presenter.pundit_user).to eq(controller.pundit_user)
end
end
end
end
describe "POST create" do
let(:creator) { create(:named_user) }
let!(:product) { create(:product, user: creator) }
context "when the creator has not enabled affiliate requests" do
it "responds with an error" do
post :create, params: { username: creator.username }, format: :json
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq false
end
end
context "when the creator has enabled affiliate requests" do
let!(:enabled_self_service_affiliate_product) { create(:self_service_affiliate_product, enabled: true, seller: creator, product:) }
context "when the request payload is invalid" do
it "responds with an error" do
post :create, params: { username: creator.username, affiliate_request: { name: "John Doe", email: "foobar", promotion_text: "hello" } }, format: :json
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Email is invalid"
end
end
context "when the request payload is valid" do
it "creates an affiliate request and notifies both the requester and the creator" do
expect_any_instance_of(AffiliateRequest).to receive(:notify_requester_and_seller_of_submitted_request).and_call_original
expect do
post :create, params: { username: creator.username, affiliate_request: { name: "John Doe", email: "john@example.com", promotion_text: "hello" } }, format: :json
end.to change { AffiliateRequest.count }.by(1)
affiliate_request = AffiliateRequest.last
expect(affiliate_request.email).to eq("john@example.com")
expect(affiliate_request.promotion_text).to eq("hello")
expect(affiliate_request.locale).to eq("en")
expect(affiliate_request.seller).to eq(creator)
expect(affiliate_request).not_to be_approved
end
context "when the requester already has an account" do
let(:requester) { create(:user) }
it "responds with 'requestor_has_account: true'" do
post :create, params: { username: creator.username, affiliate_request: { name: "John Doe", email: requester.email, promotion_text: "hello" } }, format: :json
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["requester_has_existing_account"]).to eq(true)
end
end
context "when the requester does not have an account" do
it "responds with 'requestor_has_account: false'" do
post :create, params: { username: creator.username, affiliate_request: { name: "John Doe", email: "john@example.com", promotion_text: "hello" } }, format: :json
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["requester_has_existing_account"]).to eq(false)
end
end
context "when the creator has auto-approval for affiliates enabled" do
it "approves the affiliate automatically" do
Feature.activate_user(:auto_approve_affiliates, creator)
post :create, params: { username: creator.username, affiliate_request: { name: "John Doe", email: "john@example.com", promotion_text: "hello" } }, format: :json
affiliate_request = AffiliateRequest.find_by(email: "john@example.com")
expect(affiliate_request).to be_approved
end
end
end
end
end
context "with user signed in as admin for seller" do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
describe "PATCH update" do
let(:affiliate_request) { create(:affiliate_request, seller:) }
it_behaves_like "authorize called for action", :put, :update do
let(:record) { affiliate_request }
let(:request_params) { { id: affiliate_request.external_id } }
end
context "when creator is not signed in" do
before { sign_out(seller) }
it "responds with an error" do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "approve" } }, format: :json
expect(response.parsed_body["success"]).to eq false
end
end
it "approves a request" do
expect_any_instance_of(AffiliateRequest).to receive(:make_requester_an_affiliate!)
expect do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "approve" } }, format: :json
end.to change { affiliate_request.reload.approved? }.from(false).to(true)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["affiliate_request"]["state"]).to eq("approved")
expect(response.parsed_body["requester_has_existing_account"]).to eq(false)
end
it "ignores a request" do
expect do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "ignore" } }, format: :json
end.to change { affiliate_request.reload.ignored? }.from(false).to(true)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["affiliate_request"]["state"]).to eq("ignored")
expect(response.parsed_body["requester_has_existing_account"]).to eq(false)
end
it "ignores an approved request for an affiliate who doesn't have an account" do
affiliate_request.approve!
expect do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "ignore" } }, format: :json
end.to change { affiliate_request.reload.ignored? }.from(false).to(true)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["affiliate_request"]["state"]).to eq("ignored")
expect(response.parsed_body["requester_has_existing_account"]).to eq(false)
end
it "responds with an error while ignoring an already approved request for an affiliate who has an account" do
# Ensure that the affiliate has an account
create(:user, email: affiliate_request.email)
affiliate_request.approve!
expect do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "ignore" } }, format: :json
end.to_not change { affiliate_request.reload.ignored? }
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq("John Doe's affiliate request has been already processed.")
end
it "responds with an error for an unknown action name" do
patch :update, params: { id: affiliate_request.external_id, affiliate_request: { action: "delete" } }, format: :json
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq("delete is not a valid affiliate request action")
end
end
describe "POST approve_all" do
let!(:pending_requests) { create_list(:affiliate_request, 2, seller:) }
it_behaves_like "authorize called for action", :post, :approve_all do
let(:record) { AffiliateRequest }
end
it "approves all pending affiliate requests" do
approved_request = create(:affiliate_request, seller:, state: "approved")
ignored_request = create(:affiliate_request, seller:, state: "ignored")
other_seller_request = create(:affiliate_request)
expect do
expect do
expect do
post :approve_all, format: :json
end.not_to change { approved_request.reload }
end.not_to change { ignored_request.reload }
end.not_to change { other_seller_request.reload }
expect(response).to have_http_status :ok
expect(response.parsed_body["success"]).to eq true
pending_requests.each do |request|
expect(request.reload).to be_approved
end
end
it "returns an error if there is a problem updating a record" do
allow_any_instance_of(AffiliateRequest).to receive(:approve!).and_raise(ActiveRecord::RecordInvalid)
sign_in seller
post :approve_all, format: :json
expect(response).to have_http_status :ok
expect(response.parsed_body["success"]).to eq false
end
context "when seller is signed in" do
before { sign_out(seller) }
it "returns 404" do
post :approve_all, format: :json
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq false
end
end
end
end
describe "GET approve" do
let(:affiliate_request) { create(:affiliate_request) }
before do
sign_in affiliate_request.seller
end
context "when the affiliate request is not attended yet" do
it "approves the affiliate request" do
expect do
get :approve, params: { id: affiliate_request.external_id }
end.to change { affiliate_request.reload.approved? }.from(false).to(true)
expect(response).to have_http_status(:ok)
expect(response).to render_template(:email_link_status)
expect(assigns[:message]).to eq("Approved John Doe's affiliate request.")
end
end
context "when the affiliate request is already attended" do
before(:each) do
affiliate_request.ignore!
end
it "does nothing" do
expect do
get :approve, params: { id: affiliate_request.external_id }
end.to_not change { affiliate_request.reload }
expect(response).to have_http_status(:ok)
expect(response).to render_template(:email_link_status)
expect(assigns[:message]).to eq("John Doe's affiliate request has been already processed.")
end
end
end
describe "GET ignore" do
let(:affiliate_request) { create(:affiliate_request) }
before do
sign_in affiliate_request.seller
end
context "when the affiliate request is not attended yet" do
it "ignores the affiliate request" do
expect do
get :ignore, params: { id: affiliate_request.external_id }
end.to change { affiliate_request.reload.ignored? }.from(false).to(true)
expect(response).to have_http_status(:ok)
expect(response).to render_template(:email_link_status)
expect(assigns[:message]).to eq("Ignored John Doe's affiliate request.")
end
end
context "when the affiliate request is already approved and the affiliate has an account" do
before(:each) do
# Ensure that the affiliate has an account
create(:user, email: affiliate_request.email)
affiliate_request.approve!
end
it "does nothing" do
expect do
get :ignore, params: { id: affiliate_request.external_id }
end.to_not change { affiliate_request.reload }
expect(response).to have_http_status(:ok)
expect(response).to render_template(:email_link_status)
expect(assigns[:message]).to eq("John Doe's affiliate request has been already processed.")
end
end
context "when the affiliate request is already approved and the affiliate doesn't have an account" do
before(:each) do
affiliate_request.approve!
end
it "ignores the affiliate request" do
expect do
get :ignore, params: { id: affiliate_request.external_id }
end.to_not change { affiliate_request.reload }
expect(response).to have_http_status(:ok)
expect(response).to render_template(:email_link_status)
expect(assigns[:message]).to eq("Ignored John Doe's affiliate request.")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/stripe_account_sessions_controller_spec.rb | spec/controllers/stripe_account_sessions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
RSpec.describe StripeAccountSessionsController do
let(:seller) { create(:named_seller) }
let(:connected_account_id) { "acct_123" }
before do
sign_in(seller)
end
describe "#create" do
it_behaves_like "authorize called for action", :post, :create do
let(:policy_klass) { StripeAccountSessions::UserPolicy }
let(:record) { seller }
end
context "when seller has a stripe account" do
before do
allow_any_instance_of(User).to receive(:stripe_account).and_return(double(charge_processor_merchant_id: connected_account_id))
end
it "creates a stripe account session" do
stripe_session = double(client_secret: "secret_123")
expect(Stripe::AccountSession).to receive(:create).with(
{
account: connected_account_id,
components: {
notification_banner: {
enabled: true,
features: { external_account_collection: true }
}
}
}
).and_return(stripe_session)
post :create
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(
"success" => true,
"client_secret" => "secret_123"
)
end
it "handles stripe errors" do
expect(Stripe::AccountSession).to receive(:create).and_raise(StandardError.new("Stripe error"))
expect(Bugsnag).to receive(:notify).with("Failed to create stripe account session for user #{seller.id}: Stripe error")
post :create
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(
"success" => false,
"error_message" => "Failed to create stripe account session"
)
end
end
context "when seller does not have a stripe account" do
before do
allow_any_instance_of(User).to receive(:stripe_account).and_return(nil)
end
it "returns an error" do
post :create
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to eq(
"success" => false,
"error_message" => "User does not have a Stripe account"
)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/media_locations_controller_spec.rb | spec/controllers/media_locations_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe MediaLocationsController do
describe "POST create" do
before do
@product = create(:product)
@product_file = create(:product_file, link: @product)
@purchase = create(:purchase, link: @product, purchase_state: :successful)
@url_redirect = create(:url_redirect, purchase: @purchase)
end
it "successfully creates media_location" do
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "web",
consumed_at: "2015-09-10T00:26:50.000Z",
location: 1,
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
media_location = MediaLocation.last
expect(media_location.product_file_id).to be(@product_file.id)
expect(media_location.url_redirect_id).to be(@url_redirect.id)
expect(media_location.purchase_id).to be(@purchase.id)
expect(media_location.product_id).to be(@product.id)
expect(media_location.platform).to eq(params[:platform])
expect(media_location.location).to eq(params[:location])
expect(media_location.unit).to eq MediaLocation::Unit::PAGE_NUMBER
expect(media_location.consumed_at).to eq(params[:consumed_at])
end
it "uses the url_redirect's purchase id if one is not provided" do
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android",
location: 1,
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
media_location = MediaLocation.last
expect(media_location.purchase_id).to be(@purchase.id)
end
it "creates a media_location with consumed_at set to the current_time now if one is not provided" do
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "android",
location: 1,
}
travel_to Time.current
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
media_location = MediaLocation.last
expect(media_location.consumed_at).to eq(Time.current.to_json) # to_json so it only has second precision
end
context "avoid creating new media_location if valid existing media_location is present" do
it "updates existing media_location instead of creating a new one if it exists" do
MediaLocation.create!(product_file_id: @product_file.id, product_id: @product.id, url_redirect_id: @url_redirect.id,
purchase_id: @purchase.id, platform: "web", consumed_at: "2015-09-10T00:26:50.000Z", location: 1)
expect(MediaLocation.count).to eq 1
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "web",
location: 2,
}
post(:create, params:)
expect(MediaLocation.count).to eq 1
expect(response.parsed_body["success"]).to be(true)
media_location = MediaLocation.last
expect(media_location.location).to eq(params[:location])
end
it "creates new media_location if existing media_location is present but on different platform" do
MediaLocation.create!(product_file_id: @product_file.id, product_id: @product.id, url_redirect_id: @url_redirect.id,
purchase_id: @purchase.id, platform: "web", consumed_at: "2015-09-10T00:26:50.000Z", location: 1)
expect(MediaLocation.count).to eq 1
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android",
location: 2,
}
post(:create, params:)
expect(MediaLocation.count).to eq 2
expect(response.parsed_body["success"]).to be(true)
end
end
it "ignores creating media locations for non consumable files" do
@product_file = create(:non_readable_document, link: @product)
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "web",
consumed_at: "2015-09-10T00:26:50.000Z",
location: 1,
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(false)
end
it "does not update media location if event is older than the one in db" do
MediaLocation.create!(product_file_id: @product_file.id, product_id: @product.id, url_redirect_id: @url_redirect.id,
purchase_id: @purchase.id, platform: "web", consumed_at: "2015-09-10T00:26:50.000Z", location: 1)
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "web",
consumed_at: "2015-09-10T00:24:50.000Z",
location: 1,
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(false)
expect(MediaLocation.count).to eq(1)
expect(MediaLocation.first.location).to eq(1)
end
it "updates media location if event is newer than the one in db" do
MediaLocation.create!(product_file_id: @product_file.id, product_id: @product.id, url_redirect_id: @url_redirect.id,
purchase_id: @purchase.id, platform: "web", consumed_at: "2015-09-10T00:26:50.000Z", location: 1)
params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "web",
consumed_at: "2015-09-10T00:28:50.000Z",
location: 2,
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
expect(MediaLocation.count).to eq(1)
expect(MediaLocation.first.location).to eq(2)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/customers_controller_spec.rb | spec/controllers/customers_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe CustomersController, :vcr, type: :controller, inertia: true do
render_views
let(:seller) { create(:named_user) }
include_context "with user signed in as admin for seller"
describe "GET index" do
let(:product1) { create(:product, user: seller, name: "Product 1", price_cents: 100) }
let(:product2) { create(:product, user: seller, name: "Product 2", price_cents: 200) }
let!(:purchase1) { create(:purchase, link: product1, full_name: "Customer 1", email: "customer1@gumroad.com", created_at: 1.day.ago, seller:) }
let!(:purchase2) { create(:purchase, link: product2, full_name: "Customer 2", email: "customer2@gumroad.com", created_at: 2.days.ago, seller:) }
before do
Feature.activate_user(:react_customers_page, seller)
index_model_records(Purchase)
end
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
end
it "returns HTTP success and renders the correct inertia component and props" do
get :index
expect(response).to be_successful
expect(inertia).to render_component("Customers/Index")
expect(inertia.props[:customers_presenter][:pagination]).to eq(next: nil, page: 1, pages: 1)
expect(inertia.props[:customers_presenter][:customers]).to match_array([hash_including(id: purchase1.external_id), hash_including(id: purchase2.external_id)])
expect(inertia.props[:customers_presenter][:count]).to eq(2)
end
context "for a specific product" do
it "renders the correct inertia component and props" do
get :index, params: { link_id: product1.unique_permalink }
expect(response).to be_successful
expect(inertia).to render_component("Customers/Index")
expect(inertia.props[:customers_presenter][:customers]).to match_array([hash_including(id: purchase1.external_id)])
expect(inertia.props[:customers_presenter][:product_id]).to eq(product1.external_id)
end
end
end
describe "GET paged" do
let(:product) { create(:product, user: seller, name: "Product 1", price_cents: 100) }
let!(:purchases) do
create_list :purchase, 6, seller:, link: product do |purchase, i|
purchase.update!(full_name: "Customer #{i}", email: "customer#{i}@gumroad.com", created_at: ActiveSupport::TimeZone[seller.timezone].parse("January #{i + 1} 2023"), license: create(:license, link: product, purchase:))
end
end
before do
index_model_records(Purchase)
stub_const("CustomersController::CUSTOMERS_PER_PAGE", 3)
end
it "returns HTTP success and assigns the correct instance variables" do
customer_ids = -> (res) { res.parsed_body.deep_symbolize_keys[:customers].map { _1[:id] } }
get :paged, params: { page: 2, sort: { key: "created_at", direction: "asc" } }
expect(response).to be_successful
expect(customer_ids[response]).to eq(purchases[3..].map(&:external_id))
get :paged, params: { page: 1, query: "customer0" }
expect(response).to be_successful
expect(customer_ids[response]).to eq([purchases.first.external_id])
get :paged, params: { page: 1, query: purchases.first.license.serial }
expect(response).to be_successful
expect(customer_ids[response]).to eq([purchases.first.external_id])
get :paged, params: { page: 1, created_after: ActiveSupport::TimeZone[seller.timezone].parse("January 3 2023"), created_before: ActiveSupport::TimeZone[seller.timezone].parse("January 4 2023") }
expect(response).to be_successful
expect(customer_ids[response]).to match_array([purchases.third.external_id, purchases.fourth.external_id])
end
end
describe "GET charges" do
before do
@product = create(:product, user: seller)
@subscription = create(:subscription, link: @product, user: create(:user))
@original_purchase = create(:purchase, link: @product, price_cents: 100,
is_original_subscription_purchase: true, subscription: @subscription, created_at: 1.day.ago)
@purchase1 = create(:purchase, link: @product, price_cents: 100,
is_original_subscription_purchase: false, subscription: @subscription, created_at: 1.day.from_now)
@purchase2 = create(:purchase, link: @product, price_cents: 100,
is_original_subscription_purchase: false, subscription: @subscription, created_at: 2.days.from_now)
@upgrade_purchase = create(:purchase, link: @product, price_cents: 200,
is_original_subscription_purchase: false, subscription: @subscription, created_at: 3.days.from_now, is_upgrade_purchase: true)
@new_original_purchase = create(:purchase, link: @product, price_cents: 300,
is_original_subscription_purchase: true, subscription: @subscription, created_at: 3.days.ago, purchase_state: "not_charged")
end
it_behaves_like "authorize called for action", :get, :customer_charges do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
let(:request_params) { { purchase_id: @original_purchase.external_id } }
end
let!(:chargedback_purchase) do
create(:purchase, link: @product, price_cents: 100, chargeback_date: DateTime.current,
is_original_subscription_purchase: false, subscription: @subscription, created_at: 1.day.from_now)
end
before { Feature.activate_user(:react_customers_page, seller) }
context "when purchase is an original subscription purchase" do
it "returns all recurring purchases" do
get :customer_charges, params: { purchase_id: @original_purchase.external_id, purchase_email: @original_purchase.email }
expect(response).to be_successful
expect(response.parsed_body.map { _1["id"] }).to match_array([@original_purchase.external_id, @purchase1.external_id, @purchase2.external_id, @upgrade_purchase.external_id, chargedback_purchase.external_id])
end
end
context "when purchase is a commission deposit purchase", :vcr do
let!(:commission) { create(:commission) }
before { commission.create_completion_purchase! }
it "returns the deposit and completion purchases" do
get :customer_charges, params: { purchase_id: commission.deposit_purchase.external_id, purchase_email: commission.deposit_purchase.email }
expect(response).to be_successful
expect(response.parsed_body.map { _1["id"] }).to eq([commission.deposit_purchase.external_id, commission.completion_purchase.external_id])
end
end
context "when the purchase isn't found" do
it "returns 404" do
expect do
get :customer_charges, params: { purchase_id: "fake" }
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
describe "GET customer_emails" do
it_behaves_like "authorize called for action", :get, :customer_emails do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
let(:request_params) { { purchase_id: "hello" } }
end
context "with classic product" do
before do
@product = create(:product, user: seller)
now = Time.current
@purchase = create(:purchase, link: @product, created_at: now - 15.seconds)
@post1 = create(:installment, link: @product, published_at: now - 10.seconds)
@post2 = create(:installment, link: @product, published_at: now - 5.seconds)
@post3 = create(:installment, link: @product, published_at: nil)
end
it "returns 404 if no purchase" do
expect do
get :customer_emails, params: { purchase_id: "hello" }
end.to raise_error(ActiveRecord::RecordNotFound)
end
it "returns success true with only receipt default values" do
get :customer_emails, params: { purchase_id: @purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.size).to eq 1
expect(response.parsed_body[0]["type"]).to eq("receipt")
expect(response.parsed_body[0]["id"]).to be_present
expect(response.parsed_body[0]["name"]).to eq "Receipt"
expect(response.parsed_body[0]["state"]).to eq "Delivered"
expect(response.parsed_body[0]["state_at"]).to be_present
expect(response.parsed_body[0]["url"]).to eq receipt_purchase_url(@purchase.external_id, email: @purchase.email)
end
it "returns success true with only receipt" do
create(:customer_email_info_opened, purchase: @purchase)
get :customer_emails, params: { purchase_id: @purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.size).to eq 1
expect(response.parsed_body[0]["type"]).to eq("receipt")
expect(response.parsed_body[0]["id"]).to eq(@purchase.external_id)
expect(response.parsed_body[0]["name"]).to eq "Receipt"
expect(response.parsed_body[0]["state"]).to eq "Opened"
expect(response.parsed_body[0]["state_at"]).to be_present
expect(response.parsed_body[0]["url"]).to eq receipt_purchase_url(@purchase.external_id, email: @purchase.email)
end
it "returns success true with receipt and posts" do
create(:customer_email_info_opened, purchase: @purchase)
create(:creator_contacting_customers_email_info_delivered, installment: @post1, purchase: @purchase)
create(:creator_contacting_customers_email_info_opened, installment: @post2, purchase: @purchase)
create(:creator_contacting_customers_email_info_delivered, installment: @post3, purchase: @purchase)
post_from_diff_user = create(:installment, link: @product, seller: create(:user), published_at: Time.current)
create(:creator_contacting_customers_email_info_delivered, installment: post_from_diff_user, purchase: @purchase)
get :customer_emails, params: { purchase_id: @purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.count).to eq 4
expect(response.parsed_body[0]["type"]).to eq("receipt")
expect(response.parsed_body[0]["id"]).to eq @purchase.external_id
expect(response.parsed_body[0]["state"]).to eq "Opened"
expect(response.parsed_body[0]["url"]).to eq receipt_purchase_url(@purchase.external_id, email: @purchase.email)
expect(response.parsed_body[1]["type"]).to eq("post")
expect(response.parsed_body[1]["id"]).to eq @post2.external_id
expect(response.parsed_body[1]["state"]).to eq "Opened"
expect(response.parsed_body[2]["type"]).to eq("post")
expect(response.parsed_body[2]["id"]).to eq @post1.external_id
expect(response.parsed_body[2]["state"]).to eq "Delivered"
expect(response.parsed_body[3]["type"]).to eq("post")
expect(response.parsed_body[3]["id"]).to eq @post3.external_id
expect(response.parsed_body[3]["state"]).to eq "Delivered"
end
end
context "with subscription product" do
it "returns all receipts and posts ordered by date" do
product = create(:membership_product, subscription_duration: "monthly", user: seller)
buyer = create(:user, credit_card: create(:credit_card))
subscription = create(:subscription, link: product, user: buyer)
travel_to 1.month.ago
original_purchase = create(:purchase_with_balance,
link: product,
seller: product.user,
subscription:,
purchaser: buyer,
is_original_subscription_purchase: true)
create(:customer_email_info_opened, purchase: original_purchase)
travel_back
first_post = create(:published_installment, link: product, name: "Thanks for buying!")
travel 1
recurring_purchase = create(:purchase_with_balance,
link: product,
seller: product.user,
subscription:,
purchaser: buyer)
travel 1
second_post = create(:published_installment, link: product, name: "Will you review my course?")
create(:creator_contacting_customers_email_info_opened, installment: second_post, purchase: original_purchase)
travel 1
# Second receipt email opened after the posts were published, should still be ordered by time of purchase
create(:customer_email_info_opened, purchase: recurring_purchase)
# First post delivered after second one; should still be ordered by publish time
create(:creator_contacting_customers_email_info_delivered, installment: first_post, purchase: original_purchase)
# A post sent to customers of the same product, but with filters that didn't match this purchase
unrelated_post = create(:published_installment, link: product, name: "Message to other folks!")
create(:creator_contacting_customers_email_info_delivered, installment: unrelated_post)
get :customer_emails, params: { purchase_id: original_purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.count).to eq 4
expect(response.parsed_body[0]["type"]).to eq("receipt")
expect(response.parsed_body[0]["id"]).to eq original_purchase.external_id
expect(response.parsed_body[0]["name"]).to eq "Receipt"
expect(response.parsed_body[0]["state"]).to eq "Opened"
expect(response.parsed_body[0]["url"]).to eq receipt_purchase_url(original_purchase.external_id, email: original_purchase.email)
expect(response.parsed_body[1]["type"]).to eq("receipt")
expect(response.parsed_body[1]["id"]).to eq recurring_purchase.external_id
expect(response.parsed_body[1]["name"]).to eq "Receipt"
expect(response.parsed_body[1]["state"]).to eq "Opened"
expect(response.parsed_body[1]["url"]).to eq receipt_purchase_url(recurring_purchase.external_id, email: recurring_purchase.email)
expect(response.parsed_body[2]["type"]).to eq("post")
expect(response.parsed_body[2]["id"]).to eq second_post.external_id
expect(response.parsed_body[2]["state"]).to eq "Opened"
expect(response.parsed_body[3]["type"]).to eq("post")
expect(response.parsed_body[3]["id"]).to eq first_post.external_id
expect(response.parsed_body[3]["state"]).to eq "Delivered"
end
it "includes receipts for free trial original purchases" do
product = create(:membership_product, :with_free_trial_enabled)
original_purchase = create(:membership_purchase, link: product, is_free_trial_purchase: true, purchase_state: "not_charged")
create(:customer_email_info_opened, purchase: original_purchase)
sign_in product.user
get :customer_emails, params: { purchase_id: original_purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.count).to eq 1
email_info = response.parsed_body[0]
expect(email_info["type"]).to eq("receipt")
expect(email_info["id"]).to eq original_purchase.external_id
expect(email_info["name"]).to eq "Receipt"
expect(email_info["state"]).to eq "Opened"
expect(email_info["url"]).to eq receipt_purchase_url(original_purchase.external_id, email: original_purchase.email)
end
end
context "when the purchase uses a charge receipt" do
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product) }
let(:charge) { create(:charge, purchases: [purchase], seller:) }
let(:order) { charge.order }
let!(:email_info) do
create(
:customer_email_info,
purchase_id: nil,
state: :opened,
opened_at: Time.current,
email_name: SendgridEventInfo::RECEIPT_MAILER_METHOD,
email_info_charge_attributes: { charge_id: charge.id }
)
end
before do
order.purchases << purchase
end
it "returns EmailInfo from charge" do
get :customer_emails, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body.count).to eq 1
email_info = response.parsed_body[0]
expect(email_info["type"]).to eq("receipt")
expect(email_info["id"]).to eq purchase.external_id
expect(email_info["name"]).to eq "Receipt"
expect(email_info["state"]).to eq "Opened"
expect(email_info["url"]).to eq receipt_purchase_url(purchase.external_id, email: purchase.email)
end
end
end
describe "GET missed_posts" do
before do
@product = create(:product, user: seller)
@post1 = create(:installment, link: @product, published_at: Time.current)
@post2 = create(:installment, link: @product, published_at: Time.current)
@post3 = create(:installment, link: @product, published_at: Time.current)
@unpublished_post = create(:installment, link: @product)
@purchase = create(:purchase, link: @product)
create(:creator_contacting_customers_email_info_delivered, installment: @post1, purchase: @purchase)
end
it_behaves_like "authorize called for action", :get, :missed_posts do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
let(:request_params) { { purchase_id: @purchase.external_id } }
end
it "returns success true with missed updates" do
get :missed_posts, params: { purchase_id: @purchase.external_id, purchase_email: @purchase.email }
expect(response).to be_successful
expect(response.parsed_body.count).to eq(2)
expect(response.parsed_body[0]["name"]).to eq(@post2.name)
expect(response.parsed_body[0]["published_at"].to_date).to eq(@post2.published_at.to_date)
expect(response.parsed_body[0]["url"]).to eq(custom_domain_view_post_url(host: seller.subdomain_with_protocol, slug: @post2.slug))
expect(response.parsed_body[1]["name"]).to eq(@post3.name)
expect(response.parsed_body[1]["published_at"].to_date).to eq(@post3.published_at.to_date)
expect(response.parsed_body[1]["url"]).to eq(custom_domain_view_post_url(host: seller.subdomain_with_protocol, slug: @post3.slug))
expect(response.parsed_body[2]).to eq(nil)
end
context "when the purchase is a bundle product purchase" do
it "excludes receipts" do
purchase = create(:purchase, is_bundle_product_purchase: true)
get :missed_posts, params: { purchase_id: purchase.external_id, purchase_email: purchase.email }
expect(response).to be_successful
expect(response.parsed_body).to eq([])
end
end
it "returns 404 if no purchase" do
expect do
get :missed_posts, params: { purchase_id: "hello" }
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
describe "GET product_purchases" do
let(:purchase) { create(:purchase, link: create(:product, :bundle, user: seller), seller:) }
before { purchase.create_artifacts_and_send_receipt! }
it_behaves_like "authorize called for action", :get, :missed_posts do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
let(:request_params) { { purchase_id: purchase.external_id } }
end
it "returns product purchases" do
get :product_purchases, params: { purchase_id: purchase.external_id }
expect(response.parsed_body.map(&:deep_symbolize_keys)).to eq(
purchase.product_purchases.map { CustomerPresenter.new(purchase: _1).customer(pundit_user: SellerContext.new(user: seller, seller:)) }
)
end
context "no product purchases" do
it "returns an empty array" do
get :product_purchases, params: { purchase_id: create(:purchase, seller:, link: create(:product, user: seller)).external_id }
expect(response.parsed_body).to eq([])
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/purchase_custom_fields_controller_spec.rb | spec/controllers/purchase_custom_fields_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe PurchaseCustomFieldsController do
describe "POST create" do
let(:user) { create(:user) }
let(:product) { create(:product, user: user) }
let(:purchase) { create(:purchase, link: product) }
let(:custom_field) { create(:custom_field, products: [product], type: CustomField::TYPE_TEXT, is_post_purchase: true, name: "Text input") }
describe "with valid params" do
it "creates a new purchase custom field" do
post :create, params: {
purchase_id: purchase.external_id,
custom_field_id: custom_field.external_id,
value: "Test value"
}
expect(response).to have_http_status(:no_content)
purchase_custom_field = PurchaseCustomField.last
expect(purchase_custom_field.custom_field_id).to eq(custom_field.id)
expect(purchase_custom_field.value).to eq("Test value")
expect(purchase_custom_field.field_type).to eq(CustomField::TYPE_TEXT)
expect(purchase_custom_field.purchase_id).to eq(purchase.id)
expect(purchase_custom_field.name).to eq("Text input")
end
it "updates an existing purchase custom field" do
existing_field = create(:purchase_custom_field, purchase:, custom_field:, value: "Old value", name: "Text input")
post :create, params: {
purchase_id: purchase.external_id,
custom_field_id: custom_field.external_id,
value: "New value"
}
expect(response).to have_http_status(:no_content)
existing_field.reload
expect(existing_field.custom_field_id).to eq(custom_field.id)
expect(existing_field.value).to eq("New value")
expect(existing_field.field_type).to eq(CustomField::TYPE_TEXT)
expect(existing_field.purchase_id).to eq(purchase.id)
expect(existing_field.name).to eq("Text input")
end
end
describe "file upload" do
let(:file_custom_field) { create(:custom_field, products: [product], type: CustomField::TYPE_FILE, is_post_purchase: true, name: nil) }
it "attaches files to the purchase custom field" do
file = fixture_file_upload("smilie.png", "image/png")
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: "smilie.png")
post :create, params: {
purchase_id: purchase.external_id,
custom_field_id: file_custom_field.external_id,
file_signed_ids: [blob.signed_id]
}
expect(response).to have_http_status(:no_content)
purchase_custom_field = PurchaseCustomField.last
expect(purchase_custom_field.custom_field_id).to eq(file_custom_field.id)
expect(purchase_custom_field.files).to be_attached
expect(purchase_custom_field.value).to eq("")
expect(purchase_custom_field.field_type).to eq(CustomField::TYPE_FILE)
expect(purchase_custom_field.purchase_id).to eq(purchase.id)
expect(purchase_custom_field.name).to eq(CustomField::FILE_FIELD_NAME)
end
end
describe "with invalid params" do
it "raises ActiveRecord::RecordNotFound for invalid purchase_id" do
expect do
post :create, params: {
purchase_id: "invalid_id",
custom_field_id: custom_field.external_id,
value: "Test value"
}
end.to raise_error(ActiveRecord::RecordNotFound)
end
it "raises ActiveRecord::RecordNotFound for invalid custom_field_id" do
expect do
post :create, params: {
purchase_id: purchase.external_id,
custom_field_id: "invalid_id",
value: "Test value"
}
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/affiliate_redirect_controller_spec.rb | spec/controllers/affiliate_redirect_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/affiliate_cookie_concern"
describe AffiliateRedirectController do
let(:creator) { create(:user) }
let(:product) { create(:product, user: creator) }
let(:product_2) { create(:product, user: creator) }
let(:affiliate_user) { create(:affiliate_user) }
let(:direct_affiliate) { create(:direct_affiliate, affiliate_user:, seller: creator) }
let!(:product_affiliate) { create(:product_affiliate, product:, affiliate: direct_affiliate, affiliate_basis_points: 10_00) }
before do
sign_in(creator)
end
describe "set_cookie_and_redirect" do
it "does not append anything to the redirect url if there were no url params" do
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to be_redirect
expect(response.location).not_to include("?")
expect(response.location).not_to include("affiliate_id=")
end
context "when a custom destination URL is not set" do
it "does not append anything to the redirect URL if there are no URL params" do
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to be_redirect
expect(response.location).not_to include("?")
expect(response.location).not_to include("affiliate_id=")
end
it "preserves query parameters from the original request and appends them to the redirect URL but does not implicitly add the 'affiliate_id' query parameter" do
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric, amir: "cool", you: "also_cool" }
expect(response).to be_redirect
expect(response.location).not_to include("affiliate_id=#{direct_affiliate.external_id_numeric}")
expect(response.location).to end_with("?amir=cool&you=also_cool")
end
it "redirects to the product URL" do
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to redirect_to(product.long_url)
end
end
context "when a custom destination URL is set" do
it "implicitly adds 'affiliate_id' query parameter to the final destination URL during redirect" do
direct_affiliate.update!(destination_url: "https://gumroad.com/l/abc", apply_to_all_products: true)
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to be_redirect
expect(response.location).to eq("https://gumroad.com/l/abc?affiliate_id=#{direct_affiliate.external_id_numeric}")
end
it "adds the 'affiliate_id' query parameter along with the other URL params to the redirect URL when the destination URL already contains URL params" do
direct_affiliate.update!(destination_url: "https://gumroad.com/l/abc?from=affiliate", apply_to_all_products: true)
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric, amir: "cool", you: "also_cool" }
expect(response).to be_redirect
expect(response.location).to eq("https://gumroad.com/l/abc?affiliate_id=#{direct_affiliate.external_id_numeric}&amir=cool&from=affiliate&you=also_cool")
end
it "redirects to the custom URL" do
direct_affiliate.update!(destination_url: "https://gumroad.com/l/abc", apply_to_all_products: true)
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to redirect_to("https://gumroad.com/l/abc?affiliate_id=#{direct_affiliate.external_id_numeric}")
end
end
it_behaves_like "AffiliateCookie concern" do
subject(:make_request) { get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric } }
end
context "when affiliate has no destination URL set and has multiple products" do
let(:creator) { create(:named_user) }
let(:direct_affiliate) { create(:direct_affiliate, seller: creator, products: [create(:product), create(:product)]) }
it "redirects to the creator's profile page" do
get :set_cookie_and_redirect, params: { affiliate_id: direct_affiliate.external_id_numeric }
expect(response).to redirect_to creator.subdomain_with_protocol
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/calls_controller_spec.rb | spec/controllers/calls_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe CallsController do
let(:seller) { create(:named_seller, :eligible_for_service_products) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
let(:product) { create(:call_product, :available_for_a_year, user: seller) }
let(:purchase) { create(:call_purchase, seller:, link: product) }
let(:call) { purchase.call }
include_context "with user signed in as admin for seller"
describe "PUT update" do
it_behaves_like "authorize called for action", :put, :update do
let(:policy_klass) { CallPolicy }
let(:record) { call }
let(:request_params) { { id: call.external_id } }
end
context "when the update is successful" do
it "updates the call and returns no content" do
expect do
put :update, params: { id: call.external_id, call_url: "https://zoom.us/j/thing" }, as: :json
end.to change { call.reload.call_url }.to eq("https://zoom.us/j/thing")
expect(response).to be_successful
expect(response).to have_http_status(:no_content)
end
end
context "when the call doesn't exist" do
it "returns a 404 error" do
expect { put :update, params: { id: "non_existent_id" } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/orders_controller_spec.rb | spec/controllers/orders_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
require "shared_examples/authorize_called"
include CurrencyHelper
describe OrdersController, :vcr do
before do
cookies[:_gumroad_guid] = SecureRandom.uuid
end
describe "POST create" do
let(:seller_1) { create(:user) }
let(:seller_2) { create(:user) }
let(:price_1) { 5_00 }
let(:price_2) { 10_00 }
let(:price_3) { 10_00 }
let(:price_4) { 10_00 }
let(:price_5) { 10_00 }
let(:product_1) { create(:product, user: seller_1, price_cents: price_1) }
let(:product_2) { create(:product, user: seller_1, price_cents: price_2) }
let(:product_3) { create(:product, user: seller_2, price_cents: price_3) }
let(:product_4) { create(:product, user: seller_2, price_cents: price_4) }
let(:product_5) { create(:product, user: seller_2, price_cents: price_5, discover_fee_per_thousand: 300) }
let(:payment_params) { StripePaymentMethodHelper.success.to_stripejs_params }
let(:sca_payment_params) { StripePaymentMethodHelper.success_with_sca.to_stripejs_params }
let(:pp_native_payment_params) do
{
billing_agreement_id: "B-1S519614KK328642S"
}
end
let(:common_purchase_params_without_payment) do
{
email: "buyer@gumroad.com",
cc_zipcode_required: "false",
cc_zipcode: "12345",
purchase: {
full_name: "Edgar Gumstein",
street_address: "123 Gum Road",
country: "US",
state: "CA",
city: "San Francisco",
zip_code: "94117"
}
}
end
let(:common_purchase_params) do
common_purchase_params_without_payment.merge(payment_params)
end
let(:common_purchase_params_with_sca) do
common_purchase_params_without_payment.merge(sca_payment_params)
end
let(:common_purchase_params_with_native_pp) do
common_purchase_params_without_payment.merge(pp_native_payment_params)
end
context "single purchase" do
let(:single_purchase_params) do
{
line_items: [{
uid: "unique-id-0",
permalink: product_1.unique_permalink,
perceived_price_cents: price_1,
quantity: 1
}]
}.merge(common_purchase_params)
end
it "creates an order, a charge, and a purchase" do
expect do
expect do
expect do
post :create, params: single_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(true)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end.to change(Purchase.successful, :count).by(1)
end.to change(Charge, :count).by(1)
end.to change(Order, :count).by(1)
order = Order.last
charge = Charge.last
purchase = Purchase.last
expect(order.charges).to eq([charge])
expect(order.purchases).to eq([purchase])
expect(charge.purchases).to eq([purchase])
expect(purchase.is_part_of_combined_charge?).to be true
expect(purchase.charge.amount_cents).to eq(purchase.total_transaction_cents)
expect(purchase.charge.gumroad_amount_cents).to eq(purchase.fee_cents)
expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge.id)
end
context "when purchase fails" do
let(:payment_params) { StripePaymentMethodHelper.decline.to_stripejs_params }
it "responds with success: false for specific line item" do
post :create, params: single_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(false)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end
it "creates an order and a failed purchase and a charge if purchase failed after charge attempt" do
expect do
expect do
expect do
post :create, params: single_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(false)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end.to change(Purchase.failed, :count).by(1)
end.to change(Order, :count).by(1)
end.to change(Charge, :count).by(1)
order = Order.last
charge = Charge.last
purchase = Purchase.last
expect(order.purchases.count).to eq(1)
expect(order.purchases.last).to eq(purchase)
expect(purchase.is_part_of_combined_charge?).to be true
expect(order.charges.count).to eq(1)
expect(order.charges.last).to eq(charge)
expect(SendChargeReceiptJob).not_to have_enqueued_sidekiq_job(charge.id)
end
end
context "when gifting a subscription" do
let(:subscription_price) { 10_00 }
let(:product) { create(:membership_product, price_cents: subscription_price) }
let(:single_purchase_params) do
{
is_gift: "true",
giftee_email: "giftee@gumroad.com",
gift_note: "Happy birthday!",
line_items: [{
uid: "unique-id-0",
permalink: product.unique_permalink,
perceived_price_cents: subscription_price,
quantity: 1
}]
}.merge(common_purchase_params)
end
it "creates a gift purchase" do
expect do
post :create, params: single_purchase_params
expect(response.parsed_body["success"]).to be(true)
end.to change(Purchase.successful, :count).by(1).and change(Order, :count).by(1)
subscription = product.subscriptions.last
expect(subscription).to have_attributes(
link: product,
cancelled_at: nil,
credit_card: nil,
email: "giftee@gumroad.com"
)
purchase = Purchase.successful.first
expect(purchase).to have_attributes(
is_gift_sender_purchase: true,
is_original_subscription_purchase: true
)
order = Order.last
expect(order.purchases.count).to eq(1)
expect(order.purchases.last).to eq(purchase)
gift = purchase.gift_given
expect(gift).to have_attributes(
successful?: true,
gift_note: "Happy birthday!",
giftee_email: "giftee@gumroad.com",
gifter_email: "buyer@gumroad.com"
)
expect(gift.giftee_purchase).to have_attributes(
purchase_state: "gift_receiver_purchase_successful",
is_gift_sender_purchase: false,
is_gift_receiver_purchase: true,
is_original_subscription_purchase: false,
price_cents: 0,
total_transaction_cents: 0,
displayed_price_cents: 0
)
end
end
context "when purchasing a call", :freeze_time do
before { travel_to(DateTime.parse("May 1 2024 UTC")) }
let!(:call_product) { create(:call_product, :available_for_a_year, price_cents: 10_00) }
let!(:call_duration) { 30.minutes }
let!(:call_option_30_minute) { create(:variant, name: "30 minute", duration_in_minutes: call_duration.in_minutes, variant_category: call_product.variant_categories.first) }
let!(:call_start_time) { DateTime.parse("May 1 2024 10:28:30.123456 UTC") }
let!(:normalized_call_start_time) { DateTime.parse("May 1 2024 10:28:00 UTC") }
context "with all required values" do
let(:call_purchase_params) do
{
line_items: [{
uid: "call-product-uid",
permalink: call_product.unique_permalink,
perceived_price_cents: 10_00,
quantity: 1,
variants: [call_option_30_minute.external_id],
call_start_time: call_start_time.iso8601
}]
}.merge(common_purchase_params)
end
it "creates a purchase with the correct start and end time" do
expect do
post :create, params: call_purchase_params
end.to change(Purchase.successful, :count).by(1)
purchase = Purchase.successful.last
expect(purchase.call.start_time).to eq(normalized_call_start_time)
expect(purchase.call.end_time).to eq(normalized_call_start_time + call_duration)
end
end
context "missing variant selection" do
let(:call_purchase_params) do
{
line_items: [{
uid: "call-product-uid",
permalink: call_product.unique_permalink,
perceived_price_cents: 10_00,
quantity: 1,
call_start_time: call_start_time.iso8601
}]
}.merge(common_purchase_params)
end
it "returns an error for the line item" do
post :create, params: call_purchase_params
expect(response.parsed_body["line_items"]["call-product-uid"]["error_message"]).to eq("Please select a start time.")
end
end
context "missing call start time" do
let(:call_purchase_params) do
{
line_items: [{
uid: "call-product-uid",
permalink: call_product.unique_permalink,
perceived_price_cents: 10_00,
quantity: 1,
variants: [call_option_30_minute.external_id]
}]
}.merge(common_purchase_params)
end
it "returns an error for the line item" do
post :create, params: call_purchase_params
expect(response.parsed_body["line_items"]["call-product-uid"]["error_message"]).to eq("Please select a start time.")
end
end
context "invalid call start time" do
let(:call_purchase_params) do
{
line_items: [{
uid: "call-product-uid",
permalink: call_product.unique_permalink,
perceived_price_cents: 10_00,
quantity: 1,
variants: [call_option_30_minute.external_id],
call_start_time: "invalid"
}]
}.merge(common_purchase_params)
end
it "returns an error for the line item" do
post :create, params: call_purchase_params
expect(response.parsed_body["line_items"]["call-product-uid"]["error_message"]).to eq("Please select a start time.")
end
end
context "selected time is no longer available" do
let(:call_purchase_params) do
{
line_items: [{
uid: "call-product-uid",
permalink: call_product.unique_permalink,
perceived_price_cents: 10_00,
quantity: 1,
variants: [call_option_30_minute.external_id],
call_start_time: 1.day.ago.iso8601
}]
}.merge(common_purchase_params)
end
it "returns an error for the line item" do
post :create, params: call_purchase_params
expect(response.parsed_body["line_items"]["call-product-uid"]["error_message"]).to eq("Call Selected time is no longer available")
end
end
end
describe "purchase attribution to UTM links", :sidekiq_inline do
let(:browser_guid) { "123" }
before do
cookies[:_gumroad_guid] = browser_guid
Feature.activate(:utm_links)
end
it "attributes the qualified purchase to the matching UTM link having a visit with the same browser guid" do
expect(UtmLinkSaleAttributionJob).to receive(:perform_async).with(anything, browser_guid).and_call_original
utm_link = create(:utm_link, seller: product_1.user)
utm_link_visit = create(:utm_link_visit, utm_link:, browser_guid:)
expect do
post :create, params: single_purchase_params
end.to change { utm_link.utm_link_driven_sales.count }.by(1)
order = Order.last
utm_link_driven_sale = utm_link.utm_link_driven_sales.sole
expect(utm_link_driven_sale.purchase).to eq(order.purchases.successful.sole)
expect(utm_link_driven_sale.utm_link_visit).to eq(utm_link_visit)
end
it "does not attribute purchase when there is no matching UTM link visit" do
utm_link = create(:utm_link, seller: product_1.user)
expect do
post :create, params: single_purchase_params
end.not_to change { utm_link.utm_link_driven_sales.count }
end
it "does not attribute purchase when browser guid does not match" do
utm_link = create(:utm_link, seller: product_1.user)
create(:utm_link_visit, utm_link:, browser_guid: "different_guid")
expect do
post :create, params: single_purchase_params
end.not_to change { utm_link.utm_link_driven_sales.count }
end
it "does not attribute a failed purchase" do
utm_link = create(:utm_link, seller: product_1.user)
create(:utm_link_visit, utm_link:, browser_guid:)
product_1.update!(max_purchase_count: 0)
expect do
post :create, params: single_purchase_params
end.not_to change { utm_link.utm_link_driven_sales.count }
end
it "does not attribute a purchase if the :utm_links feature is not active" do
utm_link = create(:utm_link, seller: product_1.user)
create(:utm_link_visit, utm_link:, browser_guid:)
Feature.deactivate(:utm_links)
expect do
post :create, params: single_purchase_params
end.not_to change { utm_link.utm_link_driven_sales.count }
end
end
end
context "multiple purchases" do
let(:payment_params) { StripePaymentMethodHelper.success.to_stripejs_params(prepare_future_payments: true) }
let(:multiple_purchase_params) do
{
line_items: [
{
uid: "unique-id-0",
permalink: product_1.unique_permalink,
perceived_price_cents: product_1.price_cents,
quantity: 1
},
{
uid: "unique-id-1",
permalink: product_2.unique_permalink,
perceived_price_cents: product_2.price_cents,
quantity: 1
}
]
}.merge(common_purchase_params)
end
it "creates an order, the associated purchases and a combined charge" do
expect do
expect do
expect do
post :create, params: multiple_purchase_params
end.to change(Purchase.successful, :count).by(2)
end.to change(Charge, :count).by(1)
end.to change(Order, :count).by(1)
order = Order.last
charge = Charge.last
expect(order.purchases.count).to eq(2)
expect(order.purchases.to_a).to eq(Purchase.successful.last(2))
expect(order.charges.count).to eq(1)
expect(order.charges.to_a).to eq([charge])
expect(charge.purchases.count).to eq(2)
expect(charge.amount_cents).to eq(Purchase.successful.last(2).sum(&:total_transaction_cents))
expect(charge.gumroad_amount_cents).to eq(Purchase.successful.last(2).sum(&:fee_cents))
expect(charge.stripe_payment_intent_id).to be_present
expect(charge.processor_transaction_id).to be_present
expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge.id)
end
it "creates an order, the associated purchases and a combined charge for each seller" do
multi_seller_purchase_params = {
line_items: [
{
uid: "unique-id-0",
permalink: product_1.unique_permalink,
perceived_price_cents: product_1.price_cents,
quantity: 1
},
{
uid: "unique-id-1",
permalink: product_2.unique_permalink,
perceived_price_cents: product_2.price_cents,
quantity: 1
},
{
uid: "unique-id-2",
permalink: product_3.unique_permalink,
perceived_price_cents: product_3.price_cents,
quantity: 1
},
{
uid: "unique-id-3",
permalink: product_4.unique_permalink,
perceived_price_cents: product_4.price_cents,
quantity: 1
},
{
uid: "unique-id-4",
permalink: product_5.unique_permalink,
perceived_price_cents: product_5.price_cents,
quantity: 1
}
]
}.merge(common_purchase_params)
expect do
expect do
expect do
post :create, params: multi_seller_purchase_params
end.to change(Purchase.successful, :count).by(5)
end.to change(Charge, :count).by(2)
end.to change(Order, :count).by(1)
expect(Order.last.purchases.count).to eq(5)
expect(Order.last.purchases.to_a).to eq(Purchase.successful.last(5))
expect(Order.last.charges.count).to eq(2)
expect(Order.last.charges.to_a).to eq(Charge.last(2))
charge_one = Charge.last(2).first
expect(charge_one.purchases.count).to eq(2)
expect(charge_one.amount_cents).to eq(charge_one.purchases.sum(&:total_transaction_cents))
expect(charge_one.gumroad_amount_cents).to eq(charge_one.purchases.sum(&:fee_cents))
expect(charge_one.stripe_payment_intent_id).to be_present
expect(charge_one.processor_transaction_id).to be_present
expect(charge_one.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge_one.processor_transaction_id])
expect(charge_one.purchases.pluck(:credit_card_id).uniq).to eq([charge_one.credit_card_id])
expect(charge_one.purchases.pluck(:merchant_account_id).uniq).to eq([charge_one.merchant_account_id])
expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_one.id)
charge_two = Charge.last
expect(charge_two.purchases.count).to eq(3)
expect(charge_two.purchases.is_part_of_combined_charge.count).to eq 3
expect(charge_two.amount_cents).to eq(charge_two.purchases.sum(&:total_transaction_cents))
expect(charge_two.gumroad_amount_cents).to eq(charge_two.purchases.sum(&:fee_cents))
expect(charge_two.stripe_payment_intent_id).to be_present
expect(charge_two.processor_transaction_id).to be_present
expect(charge_two.purchases.pluck(:stripe_transaction_id).uniq).to eq([charge_two.processor_transaction_id])
expect(charge_two.purchases.pluck(:credit_card_id).uniq).to eq([charge_two.credit_card_id])
expect(charge_two.purchases.pluck(:merchant_account_id).uniq).to eq([charge_two.merchant_account_id])
expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge_two.id)
end
describe "response format" do
context "when all purchases succeed" do
it "responds with success: true for every line item" do
post :create, params: multiple_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-1"]["success"]).to be(true)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end
end
context "when all purchases fail" do
let(:payment_params) { StripePaymentMethodHelper.decline.to_stripejs_params }
it "responds with success: false for every line item" do
post :create, params: multiple_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(false)
expect(response.parsed_body["line_items"]["unique-id-1"]["success"]).to be(false)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end
it "creates an order with purchases associated" do
expect do
expect do
post :create, params: multiple_purchase_params
end.to change(Purchase.failed, :count).by(2)
end.to change(Order, :count).by(1)
expect(Order.last.purchases.count).to eq(2)
expect(Order.last.purchases.to_a).to eq(Purchase.failed.last(2))
end
end
context "when some purchases fail and some succeed" do
before do
product_2.update_attribute(:max_purchase_count, 0)
end
it "responds with proper 'success' value for each line item" do
post :create, params: multiple_purchase_params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-id-1"]["success"]).to be(false)
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end
it "creates an order with purchases associated" do
expect do
expect do
expect do
expect do
post :create, params: multiple_purchase_params
end.to change(Purchase, :count).by(2)
end.to change(Purchase.successful, :count).by(1)
end.to change(Purchase.failed, :count).by(1)
end.to change(Order, :count).by(1)
expect(Order.last.purchases.count).to eq(2)
expect(Order.last.purchases.to_a).to eq([Purchase.successful.last, Purchase.failed.last])
end
end
end
context "when product is not found" do
it "handles gracefully" do
multiple_purchase_params[:line_items][1][:permalink] = "non-existent"
expect do
expect do
expect do
post :create, params: multiple_purchase_params
end.to change(Purchase.successful, :count).by(1)
end.to change(Purchase, :count).by(1)
end.to change(Order, :count).by(1)
order = Order.last
charge = Charge.last
expect(order.purchases.count).to eq(1)
expect(order.purchases.to_a).to eq([Purchase.successful.last])
expect(order.charges.count).to eq(1)
expect(charge.purchases.to_a).to eq([Purchase.successful.last])
expect(response.parsed_body["line_items"]["unique-id-0"]["success"]).to eq(true)
expect(response.parsed_body["line_items"]["unique-id-1"]["success"]).to eq(false)
expect(response.parsed_body["line_items"]["unique-id-1"]["error_message"]).to eq("Product not found")
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
expect(SendChargeReceiptJob).to have_enqueued_sidekiq_job(charge.id)
end
end
it "saves the referrer" do
multiple_purchase_params[:line_items][0][:referrer] = "https://facebook.com"
multiple_purchase_params[:line_items][1][:referrer] = "https://google.com"
post :create, params: multiple_purchase_params
expect(Purchase.second_to_last.referrer).to eq "https://facebook.com"
expect(Purchase.last.referrer).to eq "https://google.com"
end
it "creates purchase events" do
multiple_purchase_params.merge!({
referrer: "https://facebook.com",
plugins: "adblocker",
friend: "friendy"
})
multiple_purchase_params[:line_items][0][:was_product_recommended] = true
multiple_purchase_params[:line_items][1][:was_product_recommended] = false
expect do
post :create, params: multiple_purchase_params
end.to change { Event.count }.by(2)
purchase_1 = Purchase.second_to_last
event_1 = Event.second_to_last
expect(event_1.purchase_id).to eq(purchase_1.id)
expect(event_1.link_id).to eq(purchase_1.link_id)
expect(event_1.event_name).to eq("purchase")
expect(event_1.purchase_state).to eq("successful")
expect(event_1.price_cents).to eq(purchase_1.price_cents)
expect(event_1.was_product_recommended?).to eq(true)
purchase_2 = Purchase.last
event_2 = Event.last
expect(event_2.purchase_id).to eq(purchase_2.id)
expect(event_2.link_id).to eq(purchase_2.link_id)
expect(event_2.event_name).to eq("purchase")
expect(event_2.purchase_state).to eq("successful")
expect(event_2.price_cents).to eq(purchase_2.price_cents)
expect(event_2.was_product_recommended?).to eq(false)
end
it "saves recommended information" do
original_product = create(:product)
allow_any_instance_of(Link).to receive(:recommendable?).and_return(true)
multiple_purchase_params[:line_items] += [
{
uid: "unique-id-2",
permalink: product_3.unique_permalink,
perceived_price_cents: price_3,
quantity: 1,
was_product_recommended: true,
recommended_by: "search"
}, {
uid: "unique-id-3",
permalink: product_4.unique_permalink,
perceived_price_cents: price_4,
quantity: 1,
was_product_recommended: true,
recommended_by: "receipt"
}, {
uid: "unique-id-4",
permalink: product_5.unique_permalink,
perceived_price_cents: price_5,
quantity: 1,
was_product_recommended: true,
recommended_by: original_product.unique_permalink
}
]
multiple_purchase_params[:line_items][0].merge!(was_product_recommended: true, recommended_by: "discover")
multiple_purchase_params[:line_items][1].merge!(was_product_recommended: false)
post :create, params: multiple_purchase_params
purchase_1 = Purchase.first
expect(purchase_1.was_product_recommended).to eq true
expect(purchase_1.recommended_purchase_info).to be_present
expect(purchase_1.recommended_purchase_info.recommendation_type).to eq RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION
expect(purchase_1.recommended_purchase_info.recommended_link).to eq purchase_1.link
expect(purchase_1.recommended_purchase_info.recommended_by_link).to be_nil
expect(purchase_1.recommended_purchase_info.discover_fee_per_thousand).to eq(100)
expect(purchase_1.discover_fee_per_thousand).to eq(100)
purchase_2 = Purchase.second
expect(purchase_2.was_product_recommended).to eq false
expect(purchase_2.recommended_purchase_info).to be_nil
purchase_3 = Purchase.third
expect(purchase_3.was_product_recommended).to eq true
expect(purchase_3.recommended_purchase_info).to be_present
expect(purchase_3.recommended_purchase_info.recommendation_type).to eq RecommendationType::GUMROAD_SEARCH_RECOMMENDATION
expect(purchase_3.recommended_purchase_info.recommended_link).to eq purchase_3.link
expect(purchase_3.recommended_purchase_info.recommended_by_link).to be_nil
expect(purchase_3.recommended_purchase_info.discover_fee_per_thousand).to eq(100)
expect(purchase_3.discover_fee_per_thousand).to eq(100)
purchase_4 = Purchase.fourth
expect(purchase_4.was_product_recommended).to eq true
expect(purchase_4.recommended_purchase_info).to be_present
expect(purchase_4.recommended_purchase_info.recommendation_type).to eq RecommendationType::GUMROAD_RECEIPT_RECOMMENDATION
expect(purchase_4.recommended_purchase_info.recommended_link).to eq purchase_4.link
expect(purchase_4.recommended_purchase_info.recommended_by_link).to be_nil
expect(purchase_4.recommended_purchase_info.discover_fee_per_thousand).to eq(100)
expect(purchase_4.discover_fee_per_thousand).to eq(100)
purchase_5 = Purchase.fifth
expect(purchase_5.was_product_recommended).to eq true
expect(purchase_5.recommended_purchase_info).to be_present
expect(purchase_5.recommended_purchase_info.recommendation_type).to eq RecommendationType::PRODUCT_RECOMMENDATION
expect(purchase_5.recommended_purchase_info.recommended_link).to eq purchase_5.link
expect(purchase_5.recommended_purchase_info.recommended_by_link).to eq original_product
expect(purchase_5.recommended_purchase_info.discover_fee_per_thousand).to eq(300)
end
describe "chargeable construction" do
let(:payment_params) { { stripe_payment_method_id: "stripe-payment-method-id" } }
before do
cookies[:_gumroad_guid] = "random-guid"
end
it "passes in the _gumroad_guid from cookies along with the purchase params" do
expect(CardParamsHelper).to receive(:build_chargeable).with(
hash_including(stripe_payment_method_id: "stripe-payment-method-id"),
cookies[:_gumroad_guid]
)
post :create, params: multiple_purchase_params
end
end
describe "paypal native" do
let(:multiple_purchase_params_with_pp_native) do
{
line_items: [{
uid: "unique-id-0",
permalink: product_1.unique_permalink,
perceived_price_cents: price_1,
quantity: 1
}]
}.merge(common_purchase_params_with_native_pp)
end
before do
allow_any_instance_of(User).to receive(:native_paypal_payment_enabled?).and_return(true)
create(:merchant_account_paypal, user: product_1.user, charge_processor_merchant_id: "B66YJBBNCRW6L")
end
it "preserves paypal_order_id for correct charging" do
expect do
post :create, params: multiple_purchase_params_with_pp_native
end.to change { Purchase.count }.by 1
p = Purchase.successful.last
expect(p.paypal_order_id).to be_present
end
end
describe "single item purchases that require SCA" do
let(:price) { 10_00 }
let(:multiple_purchase_params_with_sca) do
common_purchase_params_with_sca.merge(
line_items: [{
uid: "unique-uid-0",
permalink: product.unique_permalink,
perceived_price_cents: price,
quantity: 1,
}]
)
end
describe "preorder" do
let(:product) { create(:product, price_cents: price, is_in_preorder_state: true) }
let!(:preorder_product) { create(:preorder_link, link: product) }
before do
allow_any_instance_of(StripeSetupIntent).to receive(:requires_action?).and_return(true)
end
it "creates an in_progress purchase and preorder and renders a proper response" do
expect do
expect do
expect do
multiple_purchase_params_with_sca[:line_items][0].merge!(is_preorder: "true")
post :create, params: multiple_purchase_params_with_sca
expect(FailAbandonedPurchaseWorker).to have_enqueued_sidekiq_job(Purchase.last.id)
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-uid-0"]["success"]).to be(true)
expect(response.parsed_body["line_items"]["unique-uid-0"]["requires_card_setup"]).to be(true)
expect(response.parsed_body["line_items"]["unique-uid-0"]["client_secret"]).to be_present
expect(response.parsed_body["can_buyer_sign_up"]).to eq(true)
end.to change(Purchase.in_progress, :count).by(1)
end.to change(Preorder.in_progress, :count).by(1)
end.to change(Order, :count).by(1)
expect(Order.last.purchases.count).to eq(1)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/recommended_products_controller_spec.rb | spec/controllers/recommended_products_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RecommendedProductsController do
describe "GET index" do
let(:recommender_model_name) { RecommendedProductsService::MODEL_SALES }
let(:cart_product) { create(:product) }
let(:products) { create_list(:product, 5) }
let(:products_relation) { Link.where(id: products.map(&:id)) }
let(:product_cards) do
products[0..2].map do |product|
ProductPresenter.card_for_web(
product:,
request:,
recommended_by:,
recommender_model_name:,
target:,
)
end
end
before do
products.last.update!(deleted_at: Time.current)
products.second_to_last.update!(archived: true)
end
let(:recommended_by) { RecommendationType::GUMROAD_MORE_LIKE_THIS_RECOMMENDATION }
let(:target) { Product::Layout::PROFILE }
let(:purchaser) { create(:user) }
let!(:purchase) { create(:purchase, purchaser:) }
before do
products.first.update!(user: purchase.link.user)
cart_product.update!(user: purchase.link.user)
index_model_records(Link)
sign_in purchaser
end
it "calls CheckoutService and returns product cards" do
expect(RecommendedProducts::CheckoutService).to receive(:fetch_for_cart).with(
purchaser:,
cart_product_ids: [cart_product.id],
recommender_model_name:,
limit: 5,
recommendation_type: nil,
).and_call_original
expect(RecommendedProductsService).to receive(:fetch).with(
{
model: RecommendedProductsService::MODEL_SALES,
ids: [cart_product.id, purchase.link.id],
exclude_ids: [cart_product.id, purchase.link.id],
number_of_results: RecommendedProducts::BaseService::NUMBER_OF_RESULTS,
user_ids: [cart_product.user.id],
}
).and_return(Link.where(id: products.first.id))
get(
:index,
params: { cart_product_ids: [cart_product.external_id], on_discover_page: "false", limit: "5" },
session: { recommender_model_name: }
)
expect(response.parsed_body).to eq([product_cards.first.with_indifferent_access])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/customer_surcharge_controller_spec.rb | spec/controllers/customer_surcharge_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomerSurchargeController, :vcr do
include ManageSubscriptionHelpers
before do
@user = create(:user)
@product = create(:product, user: @user)
@physical_product = create(:physical_product, user: @user)
country_code = Compliance::Countries::USA.alpha2
@physical_product.shipping_destinations << create(:shipping_destination, country_code:, one_item_rate_cents: 20)
@zip_tax_rate = create(:zip_tax_rate, combined_rate: 0.1, zip_code: nil, state: "CA")
end
it "returns 0 if price input is invalid" do
post "calculate_all", params: { products: [{ permalink: @physical_product.unique_permalink, price: "invalid", quantity: 1 }] }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: false,
has_vat_id_input: false,
shipping_rate_cents: 0,
tax_cents: 0,
tax_included_cents: 0,
subtotal: 0,
}.as_json)
end
it "returns the correct non-zero tax value when buyer location is EU and no VAT ID is provided" do
create(:zip_tax_rate, combined_rate: 0.19, country: "DE", state: nil, zip_code: nil, is_seller_responsible: false)
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 100, quantity: 1 }], postal_code: 10115, country: "DE" }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: false,
has_vat_id_input: true,
shipping_rate_cents: 0,
tax_cents: 19,
tax_included_cents: 0,
subtotal: 100,
}.as_json)
end
it "returns the correct tax value and an invalid VAT ID status when buyer location is EU and the VAT ID provided is invalid" do
create(:zip_tax_rate, combined_rate: 0.19, country: "DE", state: nil, zip_code: nil, is_seller_responsible: false)
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 100, quantity: 1 }], postal_code: 10115, country: "DE", vat_id: "DE123" }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: false,
has_vat_id_input: true,
shipping_rate_cents: 0,
tax_cents: 19,
tax_included_cents: 0,
subtotal: 100,
}.as_json)
end
it "returns the correct tax value when buyer location is British Columbia Canada" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 100, quantity: 1, recommended_by: "discover" }], postal_code: "V6B 2L3", country: "CA", state: "BC" }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: false,
has_vat_id_input: false,
shipping_rate_cents: 0,
tax_cents: 12,
tax_included_cents: 0,
subtotal: 100,
}.as_json)
end
it "returns tax as 0 when buyer location is EU and a valid VAT ID is provided" do
create(:zip_tax_rate, combined_rate: 0.19, country: "DE", state: nil, zip_code: nil)
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 100, quantity: 1 }], postal_code: 10115, country: "DE", vat_id: "IE6388047V" }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: true,
has_vat_id_input: false,
shipping_rate_cents: 0,
tax_cents: 0,
tax_included_cents: 0,
subtotal: 100,
}.as_json)
end
it "allows querying multiple products at once" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 100, quantity: 1 }, { permalink: @physical_product.unique_permalink, price: 200, quantity: 3 }], postal_code: 98039, country: "US" }, as: :json
expect(response.parsed_body).to eq({
vat_id_valid: false,
has_vat_id_input: false,
shipping_rate_cents: 20,
tax_cents: 32,
tax_included_cents: 0,
subtotal: 300,
}.as_json)
end
context "for a subscription", :vcr do
context "when original purchase was charged VAT" do
before :each do
setup_subscription_with_vat
end
context "and the buyer is in the EU" do
it "uses the original purchase's location info" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 500, quantity: 1, subscription_id: @subscription.external_id }], postal_code: 10115, country: "DE" }, as: :json
expect(response.parsed_body["tax_cents"]).to eq 100
end
end
context "and the buyer is currently not in the EU" do
it "still uses the original purchase's location info" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 500, quantity: 1, subscription_id: @subscription.external_id }], postal_code: 94_301, country: "US" }, as: :json
expect(response.parsed_body["tax_cents"]).to eq 100
end
end
end
context "when original purchase was not charged VAT" do
before :each do
setup_subscription
end
it "uses the original purchase's location info" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 500, quantity: 1, subscription_id: @subscription.external_id }] }, as: :json
expect(response.parsed_body["tax_cents"]).to eq 0
end
context "and the buyer is currently in the EU" do
it "still uses the original purchase's location info" do
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 500, quantity: 1, subscription_id: @subscription.external_id }], postal_code: 10115, country: "DE" }, as: :json
expect(response.parsed_body["tax_cents"]).to eq 0
expect(response.parsed_body["tax_info"]).to be_nil
end
end
end
context "when original purchase had a VAT ID" do
it "uses the VAT ID" do
allow_any_instance_of(VatValidationService).to receive(:process).and_return(true)
setup_subscription_with_vat(vat_id: "FR123456789")
post "calculate_all", params: { products: [{ permalink: @product.unique_permalink, price: 500, quantity: 1, subscription_id: @subscription.external_id }] }, as: :json
expect(response.parsed_body["tax_cents"]).to eq 0
expect(response.parsed_body["vat_id_valid"]).to eq 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/controllers/tags_controller_spec.rb | spec/controllers/tags_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TagsController do
describe "List tags" do
it "Shows matching tags alphabetically" do
%w[Armadillo Antelope Marmoset Aardvark].each { |animal| create(:tag, name: animal) }
get(:index, params: { text: "a" })
expect(response.parsed_body.length).to eq(3)
expect(response.parsed_body.first["name"]).to eq("aardvark")
expect(response.parsed_body.first["uses"]).to eq(0)
expect(response.parsed_body.last["name"]).to eq("armadillo")
expect(response.parsed_body.last["uses"]).to eq(0)
end
it "Shows popular tags first" do
5.times { create(:product).tag!("Porcupine") }
2.times { create(:product).tag!("Pangolin") }
get(:index, params: { text: "p" })
expect(response.parsed_body.first["name"]).to eq("porcupine")
expect(response.parsed_body.first["uses"]).to eq(5)
expect(response.parsed_body.last["name"]).to eq("pangolin")
expect(response.parsed_body.last["uses"]).to eq(2)
end
it "Shows success false if no text is passed in" do
get(:index)
expect(response.parsed_body["success"]).to eq(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/collaborators_controller_spec.rb | spec/controllers/collaborators_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe CollaboratorsController, inertia: true do
render_views
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:user) }
describe "GET index" do
before do
sign_in seller
end
it "renders the index template" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Collaborators/Index")
expect(inertia.props).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/controllers/subscriptions_controller_spec.rb | spec/controllers/subscriptions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe SubscriptionsController do
let(:seller) { create(:named_seller) }
let(:subscriber) { create(:user) }
before do
@product = create(:membership_product, subscription_duration: "monthly", user: seller)
@subscription = create(:subscription, link: @product, user: subscriber)
@purchase = create(:purchase, link: @product, subscription: @subscription, is_original_subscription_purchase: true)
end
context "within seller area" do
include_context "with user signed in as admin for seller"
describe "POST unsubscribe_by_seller" do
it_behaves_like "authorize called for action", :post, :unsubscribe_by_seller do
let(:record) { @subscription }
let(:request_params) { { id: @subscription.external_id } }
end
it "unsubscribes the user from the seller" do
travel_to(Time.current) do
expect do
post :unsubscribe_by_seller, params: { id: @subscription.external_id }
end.to change { @subscription.reload.user_requested_cancellation_at.try(:utc).try(:to_i) }.from(nil).to(Time.current.to_i)
expect(response).to be_successful
end
end
it "sends the correct email" do
mailer_double = double
allow(mailer_double).to receive(:deliver_later)
expect(CustomerLowPriorityMailer).to receive(:subscription_cancelled_by_seller).and_return(mailer_double)
post :unsubscribe_by_seller, params: { id: @subscription.external_id }
expect(response).to be_successful
end
end
end
context "within consumer area" do
describe "POST unsubscribe_by_user" do
before do
cookies.encrypted[@subscription.cookie_key] = @subscription.external_id
end
it "unsubscribes the user" do
travel_to(Time.current) do
expect { post :unsubscribe_by_user, params: { id: @subscription.external_id } }
.to change { @subscription.reload.user_requested_cancellation_at.try(:utc).try(:to_i) }.from(nil).to(Time.current.to_i)
end
end
it "sends the correct email" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerLowPriorityMailer).to receive(:subscription_cancelled).and_return(mail_double)
post :unsubscribe_by_user, params: { id: @subscription.external_id }
end
it "does not send the incorrect email" do
expect(CustomerLowPriorityMailer).to_not receive(:subscription_cancelled_by_seller)
post :unsubscribe_by_user, params: { id: @subscription.external_id }
end
it "returns json success" do
post :unsubscribe_by_user, params: { id: @subscription.external_id }
expect(response.parsed_body["success"]).to be(true)
end
it "is not allowed for installment plans" do
product = create(:product, :with_installment_plan, user: seller, price_cents: 30_00)
purchase_with_installment_plan = create(:installment_plan_purchase, link: product, purchaser: subscriber)
subscription = purchase_with_installment_plan.subscription
cookies.encrypted[subscription.cookie_key] = subscription.external_id
post :unsubscribe_by_user, params: { id: subscription.external_id }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error"]).to include("Installment plans cannot be cancelled by the customer")
end
context "when the encrypted cookie is not present" do
before do
cookies.encrypted[@subscription.cookie_key] = nil
end
it "renders success false with redirect_to URL" do
expect do
post :unsubscribe_by_user, params: { id: @subscription.external_id }, format: :json
end.to_not change { @subscription.reload.user_requested_cancellation_at }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["redirect_to"]).to eq(magic_link_subscription_path(@subscription.external_id))
end
end
end
describe "GET manage" do
context "when subscription has ended" do
it "returns 404" do
expect { get :manage, params: { id: @subscription.external_id } }.not_to raise_error
@subscription.end_subscription!
expect { get :manage, params: { id: @subscription.external_id } }.to raise_error(ActionController::RoutingError)
end
end
context "when installment plan is completed" do
it "returns 404" do
purchase = create(:installment_plan_purchase)
subscription = purchase.subscription
product = subscription.link
subscription.update_columns(charge_occurrence_count: product.installment_plan.number_of_installments)
(product.installment_plan.number_of_installments - 1).times do
create(:purchase, link: product, subscription: subscription, purchaser: subscription.user)
end
cookies.encrypted[subscription.cookie_key] = subscription.external_id
expect { get :manage, params: { id: subscription.external_id } }.to raise_error(ActionController::RoutingError)
end
end
context "when encrypted cookie is present" do
it "renders the manage page" do
cookies.encrypted[@subscription.cookie_key] = @subscription.external_id
get :manage, params: { id: @subscription.external_id }
expect(response).to be_successful
end
end
context "when the user is signed in" do
it "renders the manage page" do
sign_in subscriber
get :manage, params: { id: @subscription.external_id }
expect(response).to be_successful
end
end
context "when subscription is a gift" do
let(:gifter) { create(:user) }
let(:giftee) { create(:user) }
let(:product) { create(:membership_product, user: seller) }
let!(:gifted_subscription) { create(:subscription, link: product, user: giftee) }
let!(:gifter_purchase) { create(:purchase, :gift_sender, link: product, purchaser: gifter, is_original_subscription_purchase: true, subscription: gifted_subscription) }
let!(:giftee_purchase) { create(:purchase, :gift_receiver, link: product, purchaser: giftee, subscription: gifted_subscription) }
let!(:gift) { create(:gift, gifter_purchase:, giftee_purchase:, link: product) }
it "allows gifter to access manage page" do
sign_in gifter
get :manage, params: { id: gifted_subscription.external_id }
expect(response).to be_successful
end
it "allows giftee to access manage page" do
sign_in giftee
get :manage, params: { id: gifted_subscription.external_id }
expect(response).to be_successful
end
end
context "when the token param is same as subscription's token" do
it "renders the manage page" do
@subscription.update!(token: "valid_token", token_expires_at: 1.day.from_now)
get :manage, params: { id: @subscription.external_id, token: "valid_token" }
expect(response).to be_successful
end
end
context "when the token is provided but doesn't match with subscription's token" do
it "redirects to the magic link page" do
get :manage, params: { id: @subscription.external_id, token: "not_valid_token" }
expect(response).to redirect_to(magic_link_subscription_path(@subscription.external_id, invalid: true))
end
end
context "when the token is provided but it has expired" do
it "redirects to the magic link page" do
@subscription.update!(token: "valid_token", token_expires_at: 1.day.ago)
get :manage, params: { id: @subscription.external_id, token: "valid_token" }
expect(response).to redirect_to(magic_link_subscription_path(@subscription.external_id, invalid: true))
end
end
context "when it renders manage page successfully" do
it "sets subscription cookie" do
@subscription.update!(token: "valid_token", token_expires_at: 1.day.from_now)
get :manage, params: { id: @subscription.external_id, token: "valid_token" }
expect(response.cookies[@subscription.cookie_key]).to_not be_nil
end
end
it "sets X-Robots-Tag response header to avoid search engines indexing the page" do
get :manage, params: { id: @subscription.external_id }
expect(response.headers["X-Robots-Tag"]).to eq "noindex"
end
end
describe "GET magic_link" do
it "renders the magic link page" do
get :magic_link, params: { id: @subscription.external_id }
expect(response).to be_successful
end
end
describe "POST send_magic_link" do
it "sets up the token in the subscription" do
expect(@subscription.token).to be_nil
post :send_magic_link, params: { id: @subscription.external_id, email_source: "user" }
expect(@subscription.reload.token).to_not be_nil
end
it "sets the token to expire in 24 hours" do
expect(@subscription.token_expires_at).to be_nil
post :send_magic_link, params: { id: @subscription.external_id, email_source: "user" }
expect(@subscription.reload.token_expires_at).to be_within(1.second).of(24.hours.from_now)
end
it "sends the magic link email" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerMailer).to receive(:subscription_magic_link).and_return(mail_double)
post :send_magic_link, params: { id: @subscription.external_id, email_source: "user" }
expect(response).to be_successful
end
describe "email_source param" do
before do
@original_purchasing_user_email = subscriber.email
@purchase.update!(email: "purchase@email.com")
subscriber.update!(email: "subscriber@email.com")
end
context "when the email source is `user`" do
it "sends the magic link email to the user's email" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, @original_purchasing_user_email).and_return(mail_double)
post :send_magic_link, params: { id: @subscription.external_id, email_source: "user" }
expect(response).to be_successful
end
end
context "when the email source is `purchase`" do
it "sends the magic link email to the email associated to the original purchase" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, "purchase@email.com").and_return(mail_double)
post :send_magic_link, params: { id: @subscription.external_id, email_source: "purchase" }
expect(response).to be_successful
end
end
context "when the email source is `subscription`" do
it "sends the magic link email to the email associated to the subscription" do
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(CustomerMailer).to receive(:subscription_magic_link).with(@subscription.id, "subscriber@email.com").and_return(mail_double)
post :send_magic_link, params: { id: @subscription.external_id, email_source: "subscription" }
expect(response).to be_successful
end
end
context "when the email source is not valid" do
it "raises a 404 error" do
expect do
post :send_magic_link, params: { id: @subscription.external_id, email_source: "invalid source" }
end.to raise_error(ActionController::RoutingError, "Not Found")
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/controllers/followers_controller_spec.rb | spec/controllers/followers_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe FollowersController, inertia: true do
render_views
let(:seller) { create(:named_seller) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
context "within seller area" do
include_context "with user signed in as admin for seller"
describe "GET index" do
it "returns successful response with Inertia page data" do
followers = create_list(:follower, 20, user: seller) do |follower, index|
follower.update!(confirmed_at: Time.current - index.days)
end
create(:follower, user: seller, confirmed_at: Time.current - 30.days)
create(:follower, user: seller)
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Followers/Index")
expect(inertia.props).to match(hash_including(
followers: followers.map { _1.as_json(pundit_user:) },
per_page: FollowersController::FOLLOWERS_PER_PAGE,
total: 21,
))
end
end
describe "GET search" do
context "logged in" do
it "returns followers with matching emails" do
follower = create(:active_follower, user: seller)
get :search, params: { email: follower.email }
expect(response.parsed_body["paged_followers"][0]["email"]).to eq(follower.email)
end
end
context "logged out" do
it "redirects user to login" do
sign_out(seller)
get :search, params: { email: "sample" }
expect(response).to redirect_to(login_path(next: "/followers/search?email=sample"))
end
end
end
end
context "within consumer area" do
describe "GET new" do
before do
@user = create(:user, username: "dude")
get :new, params: { username: @user.username }
end
it "redirects to user profile" do
expect(response).to redirect_to(@user.profile_url)
end
end
describe "POST create" do
it "creates a follower object" do
post :create, params: { email: "follower@example.com", seller_id: seller.external_id }
follower = Follower.last
expect(follower.email).to eq "follower@example.com"
expect(follower.user).to eq seller
end
it "returns json success with a message" do
post :create, params: { email: "follower@example.com", seller_id: seller.external_id }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["message"]).to eq("Check your inbox to confirm your follow request.")
end
it "returns json error when email is invalid" do
post :create, params: { email: "invalid email", seller_id: seller.external_id }
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Email invalid.")
end
it "uncancels if follow object exists" do
follower = create(:deleted_follower, email: "follower@example.com", followed_id: seller.id)
expect { post :create, params: { email: "follower@example.com", seller_id: seller.external_id } }.to change {
follower.reload.deleted?
}.from(true).to(false)
end
describe "logged in" do
before do
@buyer = create(:user)
@params = { seller_id: seller.external_id, email: @buyer.email }
sign_in @buyer
end
it "returns json success with a message" do
post :create, params: @params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["message"]).to eq("You are now following #{seller.name_or_username}!")
end
it "creates a new follower row" do
expect { post :create, params: @params }.to change {
Follower.count
}.by(1)
end
end
describe "create follow object with email, create a user with same email, and log in" do
it "follow should update the existing follower and not create another one or throw an exception" do
post :create, params: { email: "follower@example.com", seller_id: seller.external_id }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["message"]).to eq("Check your inbox to confirm your follow request.")
follower = Follower.last
expect(follower.email).to eq "follower@example.com"
expect(follower.user).to eq seller
new_user = create(:user, email: "follower@example.com")
sign_in new_user
post :create, params: { email: "follower@example.com", seller_id: seller.external_id }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["message"]).to eq("You are now following #{seller.name_or_username}!")
expect(Follower.count).to be 1
expect(Follower.last.follower_user_id).to be new_user.id
end
end
end
describe "POST confirm" do
let(:unconfirmed_follower) { create(:follower, user: seller) }
it "confirms the follow" do
post :confirm, params: { id: unconfirmed_follower.external_id }
expect(response).to redirect_to(seller.profile_url)
expect(unconfirmed_follower.reload.confirmed_at).to_not eq(nil)
end
it "returns 404 when follower is invalid" do
expect { post :confirm, params: { id: "invalid follower" } }.to raise_error(ActionController::RoutingError)
end
it "returns 404 when seller is inactive" do
seller.deactivate!
expect do
post :confirm, params: { id: unconfirmed_follower.external_id }
end.to raise_error(ActionController::RoutingError)
end
end
describe "POST from_embed_form" do
it "creates a follower object" do
post :from_embed_form, params: { email: "follower@example.com", seller_id: seller.external_id }
follower = Follower.last
expect(follower.email).to eq "follower@example.com"
expect(follower.user).to eq seller
end
it "shows proper success messaging" do
post :from_embed_form, params: { email: "follower@example.com", seller_id: seller.external_id }
expect(response.body).to match("Followed!")
end
it "redirects to follow page on failure with proper messaging" do
post :from_embed_form, params: { email: "exampleexample.com", seller_id: seller.external_id }
expect(response).to redirect_to(seller.profile_url)
expect(flash[:warning]).to include("try to follow the creator again")
end
context "when a user is already following the creator using the same email" do
let(:following_user) { create(:user, email: "follower@example.com") }
let!(:following_relationship) { create(:active_follower, user: seller, email: following_user.email, follower_user_id: following_user.id, source: Follower::From::PROFILE_PAGE) }
it "does not create a new follower object; preserves the existing following relationship" do
expect do
post :from_embed_form, params: { email: following_user.email, seller_id: seller.external_id }
end.not_to change { Follower.count }
expect(following_relationship.follower_user_id).to eq(following_user.id)
expect(response.body).to match("Followed!")
end
end
end
describe "POST cancel" do
it "cancels the follow" do
follower = create(:follower)
expect { post :cancel, params: { id: follower.external_id } }.to change {
follower.reload.deleted?
}.from(false).to(true)
end
it "returns 404 when follower is invalid" do
expect { post :cancel, params: { id: "invalid follower" } }.to raise_error(ActionController::RoutingError)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/oauth_completions_controller_spec.rb | spec/controllers/oauth_completions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe OauthCompletionsController, :vcr do
describe "#stripe" do
let(:auth_uid) { "acct_1SOb0DEwFhlcVS6d" }
let(:referer) { settings_payments_path }
let(:user) { create(:user) }
def set_session_data
session[:stripe_connect_data] = {
"auth_uid" => auth_uid,
"referer" => referer,
"signup" => false
}
end
before do
set_session_data
sign_in user
end
context "when connecting a new Stripe account" do
it "links to existing user account" do
post :stripe
expect(user.reload.stripe_connect_account).to be_present
expect(user.stripe_connect_account.charge_processor_merchant_id).to eq(auth_uid)
expect(flash[:notice]).to eq "You have successfully connected your Stripe account!"
expect(response).to redirect_to settings_payments_url
end
it "redirects to dashboard when referer is not settings payments path" do
session[:stripe_connect_data]["referer"] = dashboard_path
post :stripe
expect(response).to redirect_to dashboard_url
end
it "shows success message for new signups" do
session[:stripe_connect_data]["signup"] = true
post :stripe
expect(flash[:notice]).to eq "You have successfully signed in with your Stripe account!"
end
it "allows connecting a Stripe account from Czechia" do
session[:stripe_connect_data]["auth_uid"] = "acct_1SOk5nRHVSLfjXtK"
post :stripe
expect(user.reload.stripe_connect_account.country).to eq("CZ")
expect(flash[:notice]).to eq "You have successfully connected your Stripe account!"
expect(response).to redirect_to settings_payments_url
end
end
context "when there are errors" do
it "handles already connected Stripe accounts" do
post :stripe
expect(user.reload.stripe_connect_account).to be_present
user2 = create(:user)
sign_in user2
set_session_data
post :stripe
expect(user2.stripe_connect_account).to be_nil
expect(flash[:alert]).to eq "This Stripe account has already been linked to a Gumroad account."
expect(response).to redirect_to settings_payments_url
end
it "allows connecting after original account is deleted" do
post :stripe
user.stripe_connect_account.delete_charge_processor_account!
user2 = create(:user)
sign_in user2
set_session_data
post :stripe
expect(user2.reload.stripe_connect_account).to be_present
expect(flash[:notice]).to eq "You have successfully connected your Stripe account!"
expect(response).to redirect_to settings_payments_url
end
it "handles merchant account creation failures" do
allow_any_instance_of(MerchantAccount).to receive(:save).and_return false
post :stripe
expect(user.stripe_connect_account).to be_nil
expect(flash[:alert]).to eq "There was an error connecting your Stripe account with Gumroad."
expect(response).to redirect_to settings_payments_url
end
it "handles invalid session data" do
session[:stripe_connect_data] = nil
post :stripe
expect(flash[:alert]).to eq "Invalid OAuth session"
expect(response).to redirect_to settings_payments_url
end
end
context "when not authenticated" do
it "requires authentication" do
sign_out user
post :stripe
expect(response).to redirect_to "/login?next=%2Foauth_completions%2Fstripe"
end
end
it "cleans up session data after completion" do
post :stripe
expect(session[:stripe_connect_data]).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/controllers/product_reviews_controller_spec.rb | spec/controllers/product_reviews_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ProductReviewsController do
let(:product) { create(:product) }
let(:purchaser) { create(:user) }
let(:purchase) { create(:purchase, link: product, purchaser: purchaser, created_at: 2.years.ago) }
let(:valid_params) do
{
link_id: product.unique_permalink,
purchase_id: purchase.external_id,
purchase_email_digest: purchase.email_digest,
rating: 4,
message: "This is my review"
}
end
describe "#set" do
context "with valid params" do
it "creates a product review" do
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(true)
purchase.reload
expect(purchase.product_review.rating).to eq(4)
expect(purchase.product_review.message).to eq("This is my review")
end
it "updates an existing review" do
review = create(:product_review, purchase: purchase, rating: 3)
put :set, params: valid_params.merge(rating: 2)
expect(response.parsed_body["success"]).to eq(true)
review.reload
expect(review.rating).to eq(2)
end
it "allows saving the same rating" do
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(true)
expect(purchase.reload.product_review.rating).to eq(4)
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(true)
expect(purchase.reload.product_review.rating).to eq(4)
end
context "video review" do
let(:video_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/video.mp4" }
let(:blob) do
ActiveStorage::Blob.create_and_upload!(
io: fixture_file_upload("test-small.jpg"),
filename: "test-small.jpg",
content_type: "image/jpeg"
)
end
it "allows creating and destroying a video review" do
put :set, params: valid_params.merge(
video_options: {
create: {
url: video_url,
thumbnail_signed_id: blob.signed_id
}
}
)
expect(response.parsed_body["success"]).to eq(true)
review = purchase.reload.product_review
expect(review.videos.count).to eq(1)
video = review.videos.first
expect(video.video_file.url).to eq(video_url)
expect(video.video_file.thumbnail.signed_id).to eq(blob.signed_id)
put :set, params: valid_params.merge(
video_options: {
destroy: { id: video.external_id }
}
)
expect(response.parsed_body["success"]).to eq(true)
expect(video.reload.deleted?).to eq(true)
end
end
end
context "with invalid params" do
it "rejects invalid email digest" do
put :set, params: valid_params.merge(purchase_email_digest: "invalid_digest")
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Sorry, you are not authorized to review this product.")
expect(purchase.reload.product_review).to be_nil
end
it "rejects missing email digest" do
put :set, params: valid_params.except(:purchase_email_digest)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Sorry, you are not authorized to review this product.")
expect(purchase.reload.product_review).to be_nil
end
it "rejects invalid rating" do
put :set, params: valid_params.merge(rating: 6)
expect(response.parsed_body["success"]).to eq(false)
expect(purchase.reload.product_review).to be_nil
end
it "rejects mismatched purchase and product" do
other_purchase = create(:purchase, purchaser: purchaser)
put :set, params: valid_params.merge(purchase_id: other_purchase.external_id)
expect(response.parsed_body["success"]).to eq(false)
expect(purchase.reload.product_review).to be_nil
end
it "rejects ineligible purchases" do
purchase.update!(stripe_refunded: true)
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Sorry, something went wrong.")
expect(purchase.reload.product_review).to be_nil
end
end
context "when seller has reviews disabled after 1 year" do
before { product.user.update!(disable_reviews_after_year: true) }
it "rejects reviews for old purchases" do
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(false)
expect(purchase.reload.product_review).to be_nil
end
it "rejects updates to old reviews" do
review = create(:product_review, purchase: purchase, rating: 2)
put :set, params: valid_params
expect(response.parsed_body["success"]).to eq(false)
expect(review.reload.rating).to eq(2)
end
end
end
describe "#index" do
let(:product) { create(:product, display_product_reviews: true) }
let!(:reviews) do
build_list(:product_review, 3, purchase: nil) do |review, i|
review.update!(purchase: create(:purchase, link: product), link: product, rating: i + 1)
review.reload
end
end
let!(:deleted_review) { create(:product_review, purchase: create(:purchase, link: product), deleted_at: Time.current) }
let!(:non_written_review) { create(:product_review, message: nil, purchase: create(:purchase, link: product)) }
before do
stub_const("ProductReviewsController::PER_PAGE", 2)
end
context "when product doesn't exist" do
it "returns not found" do
get :index, params: { product_id: "" }
expect(response).to have_http_status(:not_found)
end
end
context "when product reviews are hidden" do
before { product.update!(display_product_reviews: false) }
it "returns forbidden" do
get :index, params: { product_id: product.external_id }
expect(response).to have_http_status(:forbidden)
end
it "allows product owner to view reviews" do
sign_in product.user
get :index, params: { product_id: product.external_id }
expect(response).to be_successful
end
end
it "returns paginated product reviews" do
get :index, params: { product_id: product.external_id }
expect(response).to be_successful
expect(response.parsed_body["pagination"]).to eq({ "page" => 1, "pages" => 2 })
expect(response.parsed_body["reviews"].map(&:deep_symbolize_keys)).to eq(
reviews.reverse.first(2).map { ProductReviewPresenter.new(_1).product_review_props }
)
end
end
describe "#show" do
let(:product) { create(:product, display_product_reviews: true) }
let(:review) { create(:product_review, purchase: create(:purchase, link: product), link: product, rating: 5, message: "Great product!") }
let(:deleted_review) { create(:product_review, deleted_at: Time.current, purchase: create(:purchase, link: product), link: product) }
let(:empty_message_review) { create(:product_review, message: nil, purchase: create(:purchase, link: product), link: product) }
context "when review doesn't exist" do
it "returns not found" do
expect { get :show, params: { id: "nonexistent-id" } }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when review is deleted" do
it "returns not found" do
expect { get :show, params: { id: deleted_review.external_id } }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the review has no message nor approved videos" do
let!(:pending_video) do
create(:product_review_video, :pending_review, product_review: empty_message_review)
end
it "returns not found" do
expect { get :show, params: { id: empty_message_review.external_id } }
.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "when the review only has an approved video" do
let!(:approved_video) do
create(:product_review_video, :approved, product_review: empty_message_review)
end
it "returns the product review" do
get :show, params: { id: empty_message_review.external_id }
expect(response).to have_http_status(:ok)
expect(response.parsed_body["review"]).to match(
ProductReviewPresenter.new(empty_message_review).product_review_props
)
end
end
context "when product reviews are hidden" do
before { product.update!(display_product_reviews: false) }
it "returns forbidden" do
get :show, params: { id: review.external_id }
expect(response).to have_http_status(:forbidden)
end
it "allows product owner to view the review" do
sign_in product.user
get :show, params: { id: review.external_id }
expect(response).to be_successful
end
end
it "returns the product review" do
get :show, params: { id: review.external_id }
expect(response).to be_successful
expect(response.parsed_body["review"].deep_symbolize_keys).to eq(
ProductReviewPresenter.new(review).product_review_props
)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/consumption_analytics_controller_spec.rb | spec/controllers/consumption_analytics_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ConsumptionAnalyticsController do
describe "POST create" do
before do
@purchased_link = create(:product)
@product_file = create(:product_file, link: @purchased_link)
@purchase = create(:purchase, link: @purchased_link, purchase_state: :successful)
@url_redirect = create(:url_redirect, purchase: @purchase)
@purchaseless_url_redirect = create(:url_redirect, purchase: nil)
end
it "successfully creates consumption event" do
params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "android",
consumed_at: "2015-09-09T17:26:50PDT"
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
event = ConsumptionEvent.last
expect(event.event_type).to eq(params[:event_type])
expect(event.product_file_id).to be(@product_file.id)
expect(event.url_redirect_id).to be(@url_redirect.id)
expect(event.purchase_id).to be(@purchase.id)
expect(event.link_id).to be(@purchased_link.id)
expect(event.platform).to eq(params[:platform])
expect(event.consumed_at).to eq(params[:consumed_at])
end
it "uses the url_redirect's purchase id if one is not provided" do
params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android"
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
event = ConsumptionEvent.last
expect(event.purchase_id).to be(@purchase.id)
end
it "successfully creates a consumption event with a url_redirect that does not have a purchase" do
params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @purchaseless_url_redirect.external_id,
platform: "android"
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
event = ConsumptionEvent.last
expect(event.purchase_id).to be(nil)
end
it "creates a consumption event with consumed_at set to the current_time now if one is not provided" do
params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "android"
}
travel_to Time.current
post(:create, params:)
expect(response.parsed_body["success"]).to be(true)
event = ConsumptionEvent.last
expect(event.consumed_at).to eq(Time.current.to_json) # to_json so it only has second precision
end
it "returns failed response if event_type is invalid" do
params = {
event_type: "location_watch",
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
purchase_id: @purchase.external_id,
platform: "web"
}
post(:create, params:)
expect(response.parsed_body["success"]).to be(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/tax_center_controller_spec.rb | spec/controllers/tax_center_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe TaxCenterController, type: :controller, inertia: true do
let(:seller) { create(:user, created_at: 2.years.ago) }
before do
Feature.activate_user(:tax_center, seller)
end
describe "GET index" do
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for action", :get, :index do
let(:record) { :balance }
end
it "renders successfully" do
travel_to Time.new(2024, 6, 15) do
create(:user_tax_form, user: seller, tax_year: 2024, tax_form_type: "us_1099_k")
get :index
expect(response).to be_successful
expect(inertia.component).to eq("TaxCenter/Index")
expect(inertia.props).to include(TaxCenterPresenter.new(seller:, year: 2024).props)
expect(assigns(:title)).to eq("Payouts")
end
end
it "uses the provided year parameter" do
create(:user_tax_form, user: seller, tax_year: 2023, tax_form_type: "us_1099_k")
get :index, params: { year: 2023 }
expect(response).to be_successful
expect(inertia.props).to include(TaxCenterPresenter.new(seller:, year: 2023).props)
end
context "when tax_center feature is disabled" do
before do
Feature.deactivate_user(:tax_center, seller)
end
it "redirects to dashboard with alert" do
get :index
expect(response).to redirect_to(dashboard_path)
expect(flash[:alert]).to eq("Tax center is not enabled for your account.")
end
end
end
describe "GET download" do
include_context "with user signed in as admin for seller"
let(:year) { 2024 }
let(:form_type) { "us_1099_k" }
let(:stripe_account_id) { "acct_1234567890" }
before do
create(:user_tax_form, user: seller, tax_year: year, tax_form_type: form_type)
create(:merchant_account, user: seller, charge_processor_merchant_id: stripe_account_id)
end
it_behaves_like "authorize called for action", :get, :download do
let(:record) { :balance }
let(:policy_method) { :index? }
let(:request_params) { { year:, form_type: } }
end
it "sends the tax form PDF file" do
pdf_tempfile = Tempfile.new(["tax_form", ".pdf"])
pdf_tempfile.write("PDF content")
pdf_tempfile.rewind
allow_any_instance_of(StripeTaxFormsApi).to receive(:download_tax_form).and_return(pdf_tempfile)
get :download, params: { year:, form_type: }
expect(response).to be_successful
expect(response.headers["Content-Type"]).to eq("application/pdf")
expect(response.headers["Content-Disposition"]).to include("attachment")
expect(response.headers["Content-Disposition"]).to include("1099-K-2024.pdf")
pdf_tempfile.close
pdf_tempfile.unlink
end
context "when tax form does not exist" do
it "redirects with error message" do
get :download, params: { year: 2020, form_type: }
expect(response).to redirect_to(tax_center_path(year: 2020))
expect(flash[:alert]).to eq("Tax form not available for download.")
end
end
context "when tax form has stripe_account_id stored" do
it "uses the stored stripe_account_id if it belongs to the seller" do
tax_form = UserTaxForm.last
tax_form.stripe_account_id = stripe_account_id
tax_form.save!
pdf_tempfile = Tempfile.new(["tax_form", ".pdf"])
pdf_tempfile.write("PDF content")
pdf_tempfile.rewind
allow_any_instance_of(StripeTaxFormsApi).to receive(:download_tax_form).and_return(pdf_tempfile)
get :download, params: { year:, form_type: }
expect(response).to be_successful
pdf_tempfile.close
pdf_tempfile.unlink
end
end
context "when tax form was filed with a different Stripe account" do
let(:old_stripe_account_id) { "acct_old_account" }
before do
create(:merchant_account, user: seller, charge_processor_merchant_id: old_stripe_account_id)
tax_form = UserTaxForm.last
tax_form.stripe_account_id = old_stripe_account_id
tax_form.save!
end
it "uses the old Stripe account stored in the tax form" do
pdf_tempfile = Tempfile.new(["tax_form", ".pdf"])
pdf_tempfile.write("PDF content")
pdf_tempfile.rewind
allow_any_instance_of(StripeTaxFormsApi).to receive(:download_tax_form).and_return(pdf_tempfile)
get :download, params: { year:, form_type: }
expect(response).to be_successful
pdf_tempfile.close
pdf_tempfile.unlink
end
end
context "when stored stripe_account_id does not belong to seller" do
before do
tax_form = UserTaxForm.last
tax_form.stripe_account_id = "acct_someone_else"
tax_form.save
end
it "redirects with error message" do
get :download, params: { year:, form_type: }
expect(response).to redirect_to(tax_center_path(year:))
expect(flash[:alert]).to eq("Tax form not available for download.")
end
end
context "when download fails from Stripe API" do
before do
allow_any_instance_of(StripeTaxFormsApi).to receive(:download_tax_form).and_return(nil)
end
it "redirects with error message" do
get :download, params: { year:, form_type: }
expect(response).to redirect_to(tax_center_path(year:))
expect(flash[:alert]).to eq("Tax form not available for download.")
end
end
context "when tax_center feature is disabled" do
before do
Feature.deactivate_user(:tax_center, seller)
end
it "redirects to dashboard with alert" do
get :download, params: { year:, form_type: }
expect(response).to redirect_to(dashboard_path)
expect(flash[:alert]).to eq("Tax center is not enabled for your account.")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/two_factor_authentication_controller_spec.rb | spec/controllers/two_factor_authentication_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/merge_guest_cart_with_user_cart"
describe TwoFactorAuthenticationController do
render_views
include UsersHelper
before do
@user = create(:user, two_factor_authentication_enabled: true)
end
shared_examples_for "redirect to signed_in path for html request" do
context "when two factor authentication can be skipped" do
before do
sign_in @user
controller.reset_two_factor_auth_login_session
allow(controller).to receive(:skip_two_factor_authentication?).and_return(true)
end
context "when request format is html" do
it "redirects to signed_in_user_home" do
call_action
expect(response).to redirect_to(signed_in_user_home(@user))
end
end
end
end
shared_examples_for "respond with signed_in path for json request" do
context "when two factor authentication can be skipped" do
before do
sign_in @user
controller.reset_two_factor_auth_login_session
allow(controller).to receive(:skip_two_factor_authentication?).and_return(true)
end
context "when request format is json" do
it "responds with redirect location" do
call_action
expect(response.parsed_body["redirect_location"]).to eq signed_in_user_home(@user)
end
end
end
end
shared_examples_for "validate user_id in params for json request" do |action|
it "renders not found error in json when user_is is invalid" do
post action, params: { user_id: "invalid" }, format: :json
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["error"]).to eq "Not found"
end
end
shared_examples_for "validate user_id in params for html request" do |action|
it "raises ActionController::RoutingError when user_id is invalid" do
expect do
get action, params: { user_id: "invalid" }, format: :html
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
shared_examples_for "sign in as user and remember two factor authentication status" do
before do
controller.prepare_for_two_factor_authentication(@user)
end
it "signs in the user" do
expect(controller).to receive(:sign_in).with(@user).and_call_original
call_action
expect(controller.logged_in_user).to eq @user
end
it "invokes remember_two_factor_auth" do
expect(controller).to receive(:remember_two_factor_auth).and_call_original
call_action
end
it "invokes reset_two_factor_auth_login_session" do
expect(controller).to receive(:reset_two_factor_auth_login_session).and_call_original
call_action
end
it "confirms the user if the user is not confirmed" do
@user.update!(confirmed_at: nil)
call_action
expect(@user.reload.confirmed?).to eq true
end
end
shared_examples_for "check user in session for json request" do
it "renders not found error in json when user is not found in session" do
controller.reset_two_factor_auth_login_session
call_action
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["error"]).to eq "Not found"
end
end
shared_examples_for "check user in session for html request" do
it "raises ActionController::RoutingError when user is not found in session" do
controller.reset_two_factor_auth_login_session
expect do
call_action
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
describe "GET new" do # GET /two-factor
include_examples "redirect to signed_in path for html request" do
subject(:call_action) { get :new }
end
include_examples "check user in session for html request" do
subject(:call_action) { get :new }
end
before do
controller.prepare_for_two_factor_authentication(@user)
end
it "renders HTTP success" do
get :new
expect(response).to be_successful
expect(response).to render_template(:new)
end
it "sets @user" do
get :new
expect(assigns[:user]).to eq @user
end
end
describe "POST create" do # POST /two-factor.json
include_examples "validate user_id in params for json request", :create
include_examples "respond with signed_in path for json request" do
subject(:call_action) { post :create, format: :json }
end
include_examples "check user in session for json request" do
subject(:call_action) { post :create, format: :json }
end
before do
controller.prepare_for_two_factor_authentication(@user)
end
context "when authentication token is valid" do
include_examples "sign in as user and remember two factor authentication status" do
subject(:call_action) { post :create, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :json }
end
it "responds with success message" do
post :create, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :json
expect(response).to be_successful
expect(response.parsed_body).to eq({ "redirect_location" => controller.send(:login_path_for, @user) })
end
it_behaves_like "merge guest cart with user cart" do
let(:user) { @user }
let(:call_action) { post :create, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :json }
let(:expected_redirect_location) { controller.send(:login_path_for, @user) }
let(:expects_json_response) { true }
end
end
context "when authentication token is invalid" do
it "responds with failure message" do
post :create, params: { token: "abcdef", user_id: @user.encrypted_external_id }, format: :json
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body).to eq({ "error_message" => "Invalid token, please try again." })
end
end
end
# Request from "Login" link in authentication token email
describe "GET verify" do # GET /two-factor/verify.html
include_examples "validate user_id in params for html request", :verify
include_examples "redirect to signed_in path for html request" do
subject(:call_action) { get :verify, format: :html }
end
before do
controller.prepare_for_two_factor_authentication(@user)
end
context "when authentication token is valid" do
include_examples "sign in as user and remember two factor authentication status" do
subject(:call_action) { get :verify, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :html }
end
it "redirects with success message" do
get :verify, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :html
expect(flash[:notice]).to eq "Successfully logged in!"
expect(response).to redirect_to(controller.send(:login_path_for, @user))
end
end
context "when authentication token is invalid" do
it "redirects with failure message" do
get :verify, params: { token: "abcdef", user_id: @user.encrypted_external_id }, format: :html
expect(flash[:alert]).to eq "Invalid token, please try again."
expect(response).to redirect_to(two_factor_authentication_path)
end
end
context "when user is not available in session" do
before do
controller.reset_two_factor_auth_login_session
end
it "redirects to login_path" do
get :verify, params: { token: @user.otp_code, user_id: @user.encrypted_external_id }, format: :html
expect(response).to redirect_to(login_url(next: verify_two_factor_authentication_path(token: @user.otp_code, user_id: @user.encrypted_external_id, format: :html)))
end
end
end
describe "POST resend_authentication_token" do # POST /two-factor/resend_authentication_token.json
include_examples "validate user_id in params for json request", :resend_authentication_token
include_examples "respond with signed_in path for json request" do
subject(:call_action) { post :resend_authentication_token, format: :json }
end
include_examples "check user in session for json request" do
subject(:call_action) { post :resend_authentication_token, format: :json }
end
before do
controller.prepare_for_two_factor_authentication(@user)
end
it "resends the authentication token" do
expect do
post :resend_authentication_token, params: { user_id: @user.encrypted_external_id }, format: :json
end.to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).with(@user.id)
expect(response).to be_successful
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/users_controller_spec.rb | spec/controllers/users_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe UsersController do
render_views
let(:creator) { create(:user, username: "creator") }
let(:seller) { create(:named_seller) }
describe "GET current_user_data" do
context "when user is signed in" do
before do
sign_in seller
end
it "returns success with user data" do
timezone_name = "America/Los_Angeles"
timezone_offset = ActiveSupport::TimeZone[timezone_name].tzinfo.utc_offset
get :current_user_data
expect(response).to be_successful
expect(response.parsed_body["success"]).to be true
expect(response.parsed_body["user"]).to include(
"id" => seller.external_id,
"email" => seller.email,
"name" => seller.display_name,
"subdomain" => seller.subdomain,
"avatar_url" => seller.avatar_url,
"is_buyer" => seller.is_buyer?,
"time_zone" => {
"name" => timezone_name,
"offset" => timezone_offset
}
)
end
end
context "when user is not signed in" do
it "returns unauthorized" do
get :current_user_data
expect(response).to have_http_status(:unauthorized)
json = JSON.parse(response.body)
expect(json["success"]).to be false
end
end
end
describe "#show" do
it "404s if user isn't found in HTML format" do
expect { get :show, params: { username: "creator" }, format: :html }
.to raise_error(ActionController::RoutingError)
end
it "404s if user isn't found in JSON format" do
get :show, params: { username: "creator" }, format: :json
expect(response.status).to eq(404)
end
it "404s if no username is passed" do
expect { get :show }.to raise_error(ActionController::RoutingError)
end
it "404s if the the extension isn't html or json" do
create(:product, user: create(:user, username: "creator"), name: "onelolol")
@request.host = "creator.test.gumroad.com"
expect do
get :show, params: { username: "creator", format: "txt" }
end.to raise_error(ActionController::RoutingError)
end
it "sets a global affiliate cookie if affiliate_id is set in params" do
affiliate = create(:user).global_affiliate
user = create(:named_user)
# skip redirection to profile page
stub_const("ROOT_DOMAIN", "test.gumroad.com")
@request.host = "#{user.username}.test.gumroad.com"
get :show, params: { username: user.username, affiliate_id: affiliate.external_id_numeric }
expect(response.cookies[affiliate.cookie_key]).to be_present
end
context "when the user is deleted" do
let(:creator) { create(:user, username: "creator", deleted_at: Time.current) }
it "returns 404" do
expect do
get :show, params: { username: creator.username }
end.to raise_error(ActionController::RoutingError)
end
end
it "returns user json when json request is sent" do
link = create(:product, user: create(:user, username: "creator"), name: "onelolol")
@request.host = "creator.test.gumroad.com"
get :show, params: { username: "creator", format: "json" }
expect(response.parsed_body).to eq(link.user.as_json)
end
describe "redirection to subdomain for profile pages" do
before do
@user = create(:named_user)
end
context "when the request is from gumroad domain" do
it "redirects to subdomain profile page" do
get :show, params: { username: @user.username, sort: "price_asc" }
expect(response).to redirect_to @user.subdomain_with_protocol + "/?sort=price_asc"
expect(response).to have_http_status(:moved_permanently)
end
end
context "when the request is for the profile page on the custom domain" do
before do
create(:custom_domain, domain: "example.com", user: @user)
@request.host = "example.com"
end
it "doesn't redirect to subdomain profile page" do
get :show, params: { username: @user.username }
expect(response).to be_successful
end
end
context "when the request is for the profile page on the subdomain" do
before do
stub_const("ROOT_DOMAIN", "test.gumroad.com")
@request.host = "#{@user.username}.test.gumroad.com"
end
it "doesn't redirect to subdomain profile page" do
get :show, params: { username: @user.username }
expect(response).to be_successful
end
end
end
describe "from subdomain" do
before do
stub_const("ROOT_DOMAIN", "test.gumroad.com")
end
context "when the subdomain is valid and present" do
before do
@user = create(:user, username: "testuser")
create(:product, user: @user, name: "onelolol")
@request.host = "testuser.test.gumroad.com"
get :show
end
it "assigns the correct user based on the subdomain" do
expect(assigns(:user)).to eq(@user)
end
it "renders the show template" do
expect(response).to render_template(:show)
end
end
context "when the subdomain doesn't exist" do
before do
@request.host = "invalid.test.gumroad.com"
end
it "renders 404" do
expect { get :show }.to raise_error(ActionController::RoutingError)
end
end
end
describe "from custom domain" do
before do
allow(Resolv::DNS).to receive_message_chain(:new, :getresources).and_return([double(name: "domains.gumroad.com")])
end
describe "when the custom domain is valid" do
before do
@user = create(:user, username: "dude")
create(:product, user: @user, name: "onelolol")
@domain = CustomDomain.create(domain: "www.example1.com", user: @user)
@request.host = "www.example1.com"
get :show
end
it "assigns the correct user based on the host" do
expect(assigns(:user)).to eq(@user)
end
it "renders the show template" do
expect(response).to render_template(:show)
end
describe "when the host is another subdomain that is www with the same apex domain" do
before do
@request.host = "www.example1.com"
get :show
end
it "correctly sets the user based on the apex domain" do
expect(assigns(:user)).to eq(@user)
end
it "renders the show template" do
expect(response).to render_template(:show)
end
end
describe "when the host is another subdomain that is not www with the same apex domain" do
before do
@request.host = "store.example1.com"
end
it "404s" do
expect { get :show }.to raise_error(ActionController::RoutingError)
end
end
end
describe "when the domain requested is not saved as a custom domain" do
before do
@request.host = "not-example1.com"
end
it "404s" do
expect { get :show }.to raise_error(ActionController::RoutingError)
end
end
end
it "sets paypal_merchant_currency as merchant account's currency if native paypal payments are enabled else as usd" do
creator = create(:named_user)
create(:product, user: creator)
@request.host = "#{creator.username}.test.gumroad.com"
get :show, params: { username: creator.username }
expect(assigns[:paypal_merchant_currency]).to eq "USD"
create(:merchant_account_paypal, user: creator, currency: "GBP")
get :show, params: { username: creator.username }
expect(assigns[:paypal_merchant_currency]).to eq "GBP"
end
context "with user signed in as admin for seller" do
let(:seller) { create(:named_seller) }
let(:creator) { create(:user, username: "creator") }
include_context "with user signed in as admin for seller"
it "assigns the correct instance variables" do
expect(ProfilePresenter).to receive(:new).with(seller: creator, pundit_user: controller.pundit_user).at_least(:once).and_call_original
@request.host = "#{creator.username}.test.gumroad.com"
get :show, params: { username: creator.username }
profile_props = assigns[:profile_props]
expect(profile_props[:creator_profile][:external_id]).to eq(creator.external_id)
end
end
describe "Elasticsearch queries cache", :sidekiq_inline, :elasticsearch_wait_for_refresh do
it "caches @search_results and tracks cache hits/misses" do
metrics_key = "#{ProfileSectionsPresenter::CACHE_KEY_PREFIX}-metrics"
$redis.del(metrics_key)
user = create(:user, username: "testuser")
product = create(:product, user:)
create(:seller_profile_products_section, seller: user, shown_products: [product.id])
@request.host = "testuser.test.gumroad.com"
get :show
expect($redis.hgetall(metrics_key)).to eq("misses" => "1")
get :show
expect($redis.hgetall(metrics_key)).to eq("misses" => "1", "hits" => "1")
product.update!(name: "something else")
get :show
expect($redis.hgetall(metrics_key)).to eq("misses" => "2", "hits" => "1")
end
end
it "truncates the bio when it's longer than 300 characters" do
@request.host = seller.subdomain
seller.update!(bio: "f" * 301)
get :show, params: { username: seller.username }
expect(response.body).to have_selector("meta[name='description'][content='#{"f" * 300}']", visible: false)
end
end
describe "GET coffee" do
let(:seller) { create(:user, :eligible_for_service_products) }
render_views
context "user has coffee product" do
let!(:product) { create(:product, name: "Buy me a coffee", user: seller, native_type: Link::NATIVE_TYPE_COFFEE, purchase_disabled_at: Time.current) }
it "responds successfully and sets the title" do
get :coffee, params: { username: seller.username }
expect(response).to be_successful
expect(response.body).to have_selector("title:contains('Buy me a coffee')", visible: false)
end
end
context "user doesn't have coffee product" do
let!(:product) { create(:coffee_product, user: seller, archived: true) }
it "returns a 404" do
expect do
get :coffee, params: { username: seller.username }
end.to raise_error(ActionController::RoutingError)
end
end
end
describe "GET session_info" do
context "when user is not signed in" do
it "returns json with is_signed_in: false" do
get :session_info
expect(response).to be_successful
expect(response.parsed_body["is_signed_in"]).to eq false
end
end
context "when user is signed in" do
before do
sign_in create(:user)
end
it "returns json with is_signed_in: true" do
get :session_info
expect(response).to be_successful
expect(response.parsed_body["is_signed_in"]).to eq true
end
end
end
describe "#deactivate" do
let(:user) { create(:user, username: "ohai") }
it "redirects if user is not authenticated" do
post :deactivate
expect(response).to redirect_to login_url(next: request.path)
expect(user.reload.deleted_at).to be(nil)
end
context "when user is authenticated" do
context "when current user doesn't match current seller" do
let (:other_user) { create(:user) }
include_context "with user signed in as admin for seller"
it "redirects" do
post :deactivate
expect(response).to redirect_to dashboard_path
expect(flash[:alert]).to eq("Your current role as Admin cannot perform this action.")
expect(user.deleted_at).to be(nil)
end
end
context "when current user matches current seller" do
before :each do
sign_in user
end
it_behaves_like "authorize called for action", :post, :deactivate do
let(:record) { user }
let(:policy_method) { :deactivate? }
end
context "when user is successfully deactivated" do
it "signs user out" do
expect(controller).to receive(:sign_out)
post :deactivate
end
it "succeeds" do
post :deactivate
expect(response.parsed_body["success"]).to be(true)
end
it "deletes all of the users products, product files, bank accounts, credit card, compliance infos.", :vcr, :elasticsearch_wait_for_refresh, :sidekiq_inline do
create(:user_compliance_info, user:, individual_tax_id: "123456789")
create(:ach_account, user:)
link = create(:product, user:)
link.product_files << create(:product_file, link:)
link.product_files << create(:product_file, link:, is_linked_to_existing_file: true)
link2 = create(:product, user:)
link2.product_files << create(:product_file, link: link2)
link2.product_files << create(:product_file, link: link2, is_linked_to_existing_file: true)
create(:purchase, link: link2, purchase_state: "successful")
user.credit_card = create(:credit_card)
user.save!
expect(user.reload.deleted_at).to be(nil)
expect(user.user_compliance_infos.alive.size).to eq(1)
expect(user.bank_accounts.alive.size).to eq(1)
expect(user.links.alive.size).to eq(2)
expect(link.product_files.alive.size).to eq(2)
expect(link2.product_files.alive.size).to eq(2)
expect(user.credit_card_id).not_to be(nil)
post :deactivate
[link, link2, user].each(&:reload)
expect(user.deleted_at).not_to be(nil)
expect(user.user_compliance_infos.alive.size).to eq(0)
expect(user.bank_accounts.alive.size).to eq(0)
expect(user.links.alive.size).to eq(0)
expect(link.product_files.alive.size).to eq(0)
expect(link2.product_files.alive.size).to eq(2)
expect(user.credit_card_id).to be(nil)
end
it "deactivates the user account only if balance amount is 0" do
create(:balance, user:, amount_cents: 10)
create(:balance, user:, amount_cents: 11, date: 1.day.ago)
post :deactivate
expect(response.parsed_body["success"]).to eq(false)
expect(user.reload.deleted_at).to be(nil)
create(:balance, user:, amount_cents: -30, date: 2.days.ago)
post :deactivate
expect(response.parsed_body["success"]).to eq(false)
expect(user.reload.deleted_at).to be(nil)
create(:balance, user:, amount_cents: 9, date: 3.days.ago)
post :deactivate
expect(response.parsed_body["success"]).to eq(true)
expect(user.reload.deleted_at).not_to be(nil)
end
it "sets deleted_at to non nil value" do
post :deactivate
expect(user.reload.deleted_at).to_not be(nil)
end
it "frees up the username" do
post :deactivate
expect(user.reload.read_attribute(:username)).to be(nil)
end
it "pauses payouts" do
post :deactivate
expect(user.reload.payouts_paused_internally?).to be(true)
end
it "logs out the user from all active sessions" do
travel_to(DateTime.current) do
expect do
post :deactivate
end.to change { user.reload.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current)
end
end
end
context "when user is not successfully deactivated" do
before :each do
allow(controller.logged_in_user).to receive(:update!).and_raise
end
it "fails" do
post :deactivate
expect(response.parsed_body["success"]).to be(false)
end
it "does not set deleted_at to non nil value" do
post :deactivate
expect(user.reload.deleted_at).to be(nil)
end
end
context "when the user has unpaid balances" do
before :each do
@balance = create(:balance, user:, amount_cents: 656)
end
context "when feature delete_account_forfeit_balance is active" do
before do
stub_const("GUMROAD_ADMIN_ID", create(:admin_user).id) # For negative credits
Feature.activate_user(:delete_account_forfeit_balance, user)
end
it "succeeds" do
post :deactivate
expect(user.reload.deleted_at).to_not be(nil)
expect(@balance.reload.state).to eq("forfeited")
end
end
context "when feature delete_account_forfeit_balance is inactive" do
it "fails" do
post :deactivate
expect(response.parsed_body["success"]).to be(false)
expect(user.reload.deleted_at).to be(nil)
expect(user.unpaid_balance_cents).to eq(656)
expect(@balance.reload.state).to eq("unpaid")
end
end
end
end
end
end
describe "#email_unsubscribe" do
before do
@user = create(:user, enable_payment_email: true, weekly_notification: true)
end
context "with secure external id" do
it "allows access with valid secure external id" do
secure_id = @user.secure_external_id(scope: "email_unsubscribe")
get :email_unsubscribe, params: { email_type: "notify", id: secure_id }
expect(@user.reload.enable_payment_email).to be(false)
expect(response).to redirect_to(root_path)
end
end
context "with regular external id when user exists" do
it "redirects to secure redirect page for confirmation" do
get :email_unsubscribe, params: { email_type: "notify", id: @user.external_id }
expect(response).to be_redirect
expect(response.location).to start_with(secure_url_redirect_url)
expect(response.location).to include("encrypted_payload")
expect(response.location).to include("message=Please+enter+your+email+address+to+unsubscribe")
expect(response.location).to include("field_name=Email+address")
expect(response.location).to include("error_message=Email+address+does+not+match")
end
it "includes correct destination URL in redirect params" do
allow(SecureEncryptService).to receive(:encrypt).and_call_original
get :email_unsubscribe, params: { email_type: "seller_update", id: @user.external_id }
expect(SecureEncryptService).to have_received(:encrypt).once
# Verify that the encrypted payload contains the expected data
encrypted_payload = URI.decode_www_form(URI.parse(response.location).query).to_h["encrypted_payload"]
decrypted_payload = JSON.parse(SecureEncryptService.decrypt(encrypted_payload))
expect(decrypted_payload["destination"]).to match(%r{/unsubscribe/.*email_type=seller_update})
expect(decrypted_payload["confirmation_texts"]).to include(@user.email)
end
it "includes encrypted user email for confirmation" do
allow(SecureEncryptService).to receive(:encrypt).and_call_original
get :email_unsubscribe, params: { email_type: "product_update", id: @user.external_id }
expect(SecureEncryptService).to have_received(:encrypt).once
# Verify that the encrypted payload contains the expected data
encrypted_payload = URI.decode_www_form(URI.parse(response.location).query).to_h["encrypted_payload"]
decrypted_payload = JSON.parse(SecureEncryptService.decrypt(encrypted_payload))
expect(decrypted_payload["confirmation_texts"]).to include(@user.email)
end
end
context "with signed in user matching the external id" do
it "allows access without redirect" do
sign_in(@user)
get :email_unsubscribe, params: { email_type: "notify", id: @user.external_id }
expect(@user.reload.enable_payment_email).to be(false)
expect(response).to redirect_to(root_path)
end
end
context "with invalid external id" do
it "raises 404 error" do
expect do
get :email_unsubscribe, params: { email_type: "notify", id: "invalid_id" }
end.to raise_error(ActionController::RoutingError)
end
end
describe "payment_notifications" do
it "redirects home, sets column correctly" do
secure_id = @user.secure_external_id(scope: "email_unsubscribe")
get :email_unsubscribe, params: { email_type: "notify", id: secure_id }
expect(@user.reload.enable_payment_email).to be(false)
end
end
describe "weekly notifications" do
it "redirects home, sets column correctly" do
secure_id = @user.secure_external_id(scope: "email_unsubscribe")
get :email_unsubscribe, params: { email_type: "seller_update", id: secure_id }
expect(@user.reload.weekly_notification).to be(false)
end
end
describe "announcement notifications" do
it "redirects home, sets column correctly" do
secure_id = @user.secure_external_id(scope: "email_unsubscribe")
get :email_unsubscribe, params: { email_type: "product_update", id: secure_id }
expect(@user.reload.announcement_notification_enabled).to be(false)
end
end
end
describe "#add_purchase_to_library" do
before do
@user = create(:user, username: "dude", password: "password")
@purchase = create(:purchase, email: @user.email)
@params = {
"user" => {
"password" => "password",
"purchase_id" => @purchase.external_id,
"purchase_email" => @purchase.email
}
}
end
it "associates the purchase to the signed_in user" do
sign_in(@user)
post :add_purchase_to_library, params: @params
expect(@purchase.reload.purchaser).to eq @user
end
it "associates the purchase to the user if the password is correct" do
post :add_purchase_to_library, params: @params
expect(@purchase.reload.purchaser).to eq @user
end
it "doesn't associate the purchase with the user if the password is incorrect" do
@params["user"]["password"] = "wrong password"
post :add_purchase_to_library, params: @params
expect(@purchase.reload.purchaser).to be(nil)
end
it "doesn't associate the purchase if the email doesn't match" do
@params["user"]["purchase_email"] = "wrong@example.com"
post :add_purchase_to_library, params: @params
expect(@purchase.reload.purchaser).to be(nil)
end
context "when two factor authentication is enabled for the user" do
before do
@user.two_factor_authentication_enabled = true
@user.save!
end
it "invokes sign_in_or_prepare_for_two_factor_auth" do
expect(controller).to receive(:sign_in_or_prepare_for_two_factor_auth).with(@user).and_call_original
@params["user"]["password"] = "password"
post :add_purchase_to_library, params: @params
end
it "redirects to two_factor_authentication_with with next param set to library path" do
@params["user"]["password"] = "password"
post :add_purchase_to_library, params: @params
expect(response.parsed_body["success"]).to eq true
expect(response.parsed_body["redirect_location"]).to eq two_factor_authentication_path(next: library_path)
end
end
end
describe "GET subscribe" do
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
it "assigns the correct instance variables" do
@request.host = "#{creator.username}.test.gumroad.com"
get :subscribe
expect(assigns[:title]).to eq("Subscribe to creator")
profile_presenter = assigns[:profile_presenter]
expect(profile_presenter.seller).to eq(creator)
expect(profile_presenter.pundit_user).to eq(controller.pundit_user)
end
end
end
describe "GET subscribe_preview" do
it "assigns subscribe preview props for the react component" do
get :subscribe_preview, params: { username: creator.username }
expect(response).to be_successful
expect(assigns[:subscribe_preview_props][:title]).to eq(creator.name_or_username)
expect(assigns[:subscribe_preview_props][:avatar_url]).to end_with(".png")
end
end
describe "GET unsubscribe_review_reminders" do
before do
@user = create(:user)
end
context "when user is logged in" do
it "sets opted_out_of_review_reminders flag successfully" do
sign_in(@user)
expect do
get :unsubscribe_review_reminders
end.to change { @user.reload.opted_out_of_review_reminders? }.from(false).to(true)
expect(response).to be_successful
end
end
context "when user is not logged in" do
it "redirects to login page" do
sign_out(@user)
get :unsubscribe_review_reminders
expect(response).to redirect_to(login_url(next: user_unsubscribe_review_reminders_path))
end
end
end
describe "GET subscribe_review_reminders" do
before do
@user = create(:user, opted_out_of_review_reminders: true)
end
context "when user is logged in" do
it "sets opted_out_of_review_reminders flag successfully" do
sign_in(@user)
expect do
get :subscribe_review_reminders
end.to change { @user.reload.opted_out_of_review_reminders? }.from(true).to(false)
expect(response).to be_successful
end
end
context "when user is not logged in" do
it "redirects to login page" do
sign_out(@user)
get :subscribe_review_reminders
expect(response).to redirect_to(login_url(next: user_subscribe_review_reminders_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/controllers/confirmations_controller_spec.rb | spec/controllers/confirmations_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe ConfirmationsController do
before do
request.env["devise.mapping"] = Devise.mappings[:user]
@user = create(:user, confirmed_at: nil)
end
describe "#show" do
describe "already confirmed" do
before do
@confirmation_token = @user.confirmation_token
@user.confirm
end
it "redirects home" do
get :show, params: { confirmation_token: @confirmation_token }
expect(response).to redirect_to root_url
end
end
describe "logged in" do
before do
sign_in @user
end
it "confirms the user" do
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to change {
@user.reload.confirmed?
}.from(false).to(true)
end
end
describe "logged out" do
it "redirects user to settings page after confirmation" do
get :show, params: { confirmation_token: @user.confirmation_token }
expect(response).to redirect_to dashboard_url
end
it "confirms the user" do
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to change {
@user.reload.confirmed?
}.from(false).to(true)
end
it "logs in the user" do
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to change {
subject.logged_in_user.nil?
}.from(true).to(false)
end
it "invalidates the user's active sessions and keeps the current session active" do
old_email = @user.email
@user.update!(unconfirmed_email: "new@example.com")
freeze_time do
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to change { @user.reload.email }.from(old_email).to("new@example.com")
.and change { @user.unconfirmed_email }.from("new@example.com").to(nil)
.and change { @user.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current)
expect(request.env["warden"].session["last_sign_in_at"]).to eq(DateTime.current.to_i)
end
end
context "when the user has requested password reset instructions" do
before do
@user.send_reset_password_instructions
end
it "invalidates the user's reset password token" do
expect(@user.reset_password_token).to be_present
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to change { @user.reload.reset_password_token }.to(nil)
.and change { @user.reset_password_sent_at }.to(nil)
end
end
context "when user is already confirmed" do
before do
@user.confirm
end
it "does not invalidate the user's active sessions" do
expect do
get :show, params: { confirmation_token: @user.confirmation_token }
end.to_not change { @user.reload.last_active_sessions_invalidated_at }
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/controllers/commissions_controller_spec.rb | spec/controllers/commissions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe CommissionsController, :vcr do
let(:seller) { create(:named_seller, :eligible_for_service_products) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
let(:commission) { create(:commission, deposit_purchase: create(:purchase, seller:, link: create(:commission_product, user: seller), price_cents: 100, displayed_price_cents: 100, credit_card: create(:credit_card))) }
include_context "with user signed in as admin for seller"
describe "PUT update" do
it_behaves_like "authorize called for action", :put, :update do
let(:policy_klass) { CommissionPolicy }
let(:record) { commission }
let(:request_params) { { id: commission.external_id } }
end
it "attaches new files and purges old files" do
allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil)
commission.files.attach(file_fixture("test.png"))
file = fixture_file_upload("test.pdf")
blob = ActiveStorage::Blob.create_and_upload!(io: file, filename: "test.pdf")
expect do
put :update, params: { id: commission.external_id, file_signed_ids: [blob.signed_id] }, as: :json
end.to_not change { commission.reload.files.count }
expect(response).to be_successful
expect(response).to have_http_status(:no_content)
expect(commission.files.first.filename).to eq("test.pdf")
end
context "when commission is not found" do
it "raises an ActiveRecord::RecordNotFound error" do
expect do
put :update, params: { id: "non_existent_id", file_signed_ids: [] }
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
describe "POST complete" do
it_behaves_like "authorize called for action", :post, :complete do
let(:policy_klass) { CommissionPolicy }
let(:record) { commission }
let(:request_params) { { id: commission.external_id } }
end
it "creates a completion purchase" do
expect_any_instance_of(Commission).to receive(:create_completion_purchase!).and_call_original
post :complete, params: { id: commission.external_id }
expect(response).to be_successful
expect(response).to have_http_status(:no_content)
commission.reload
expect(commission.completion_purchase).to be_present
expect(commission.status).to eq(Commission::STATUS_COMPLETED)
end
context "when an error occurs during completion" do
it "returns an error message" do
allow_any_instance_of(Commission).to receive(:create_completion_purchase!).and_raise(ActiveRecord::RecordInvalid.new)
post :complete, params: { id: commission.external_id }
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body).to eq({ "errors" => ["Failed to complete commission"] })
end
end
context "when commission is not found" do
it "raises an ActiveRecord::RecordNotFound error" do
expect do
post :complete, params: { id: "non_existent_id" }
end.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/braintree_controller_spec.rb | spec/controllers/braintree_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe BraintreeController, :vcr do
describe "#client_token" do
it "returns client token in json on success" do
get :client_token
response_hash = response.parsed_body
expect(response_hash["clientToken"].present?).to be true
end
it "returns nil in response on failure" do
allow(Braintree::ClientToken).to receive(:generate).and_raise(Braintree::ServerError)
get :client_token
expect(response.body).to eq({ clientToken: nil }.to_json)
end
end
describe "#generate_transient_customer_token" do
it "does not return anything if the nonce or the Gumroad GUID is missing" do
cookies[:_gumroad_guid] = ""
post :generate_transient_customer_token, params: { braintree_nonce: Braintree::Test::Nonce::PayPalFuturePayment }
expect(response.body).to eq({ transient_customer_store_key: nil }.to_json)
cookies[:_gumroad_guid] = "we-need-a-guid"
post :generate_transient_customer_token
expect(response.body).to eq({ transient_customer_store_key: nil }.to_json)
end
it "returns a cached key when the guid is available and the nonce is valid" do
cookies[:_gumroad_guid] = "we-need-a-guid"
post :generate_transient_customer_token, params: { braintree_nonce: Braintree::Test::Nonce::PayPalFuturePayment }
expect(response.body).to_not eq({ transient_customer_store_key: nil }.to_json)
parsed_body = response.parsed_body
expect(parsed_body["transient_customer_store_key"]).to_not be(nil)
end
it "returns an error message when the nonce is invalid" do
cookies[:_gumroad_guid] = "we-need-a-guid"
post :generate_transient_customer_token, params: { braintree_nonce: "invalid" }
expect(response.body).to eq({ error: "Please check your card information, we couldn't verify it." }.to_json)
end
it "returns an error message when the charge processor is down" do
expect(BraintreeChargeableTransientCustomer).to receive(:tokenize_nonce_to_transient_customer).and_raise(ChargeProcessorUnavailableError)
cookies[:_gumroad_guid] = "we-need-a-guid"
post :generate_transient_customer_token, params: { braintree_nonce: Braintree::Test::Nonce::PayPalFuturePayment }
expect(response.body).to eq({ error: "There is a temporary problem, please try again (your card was not charged)." }.to_json)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/imported_customers_controller_spec.rb | spec/controllers/imported_customers_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe ImportedCustomersController do
let(:seller) { create(:named_user) }
describe "GET index" do
include_context "with user signed in as admin for seller"
before do
@product = create(:product, user: seller)
35.times do
create(:purchase, link: @product)
end
35.times do
create(:imported_customer, link_id: @product.id, importing_user: seller)
end
end
it_behaves_like "authorize called for action", :get, :index do
let(:record) { ImportedCustomer }
end
it "returns the correct number of imported customers on first page" do
get :index, params: { link_id: @product.unique_permalink, page: 0 }
expect(response.parsed_body["customers"].length).to eq 20
expect(response.parsed_body["begin_loading_imported_customers"]).to eq true
end
it "returns the correct number of imported customers on last page" do
get :index, params: { link_id: @product.unique_permalink, page: 1 }
expect(response.parsed_body["customers"].length).to eq 15
expect(response.parsed_body["begin_loading_imported_customers"]).to eq true
end
end
describe "DELETE destroy" do
include_context "with user signed in as admin for seller"
let(:imported_customer) { create(:imported_customer, importing_user: seller) }
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { imported_customer }
let(:request_params) { { id: imported_customer.external_id } }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/secure_redirect_controller_spec.rb | spec/controllers/secure_redirect_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SecureRedirectController, type: :controller do
let(:destination_url) { user_unsubscribe_url(id: "sample-id", email_type: "notify") }
let(:confirmation_text) { "user@example.com" }
let(:secure_payload) do
{
destination: destination_url,
confirmation_texts: [confirmation_text],
created_at: Time.current.to_i
}
end
let(:encrypted_payload) { SecureEncryptService.encrypt(secure_payload.to_json) }
let(:message) { "Please confirm your email address" }
let(:field_name) { "Email address" }
let(:error_message) { "Email address does not match" }
describe "GET #new" do
context "with valid params" do
it "renders the new template" do
get :new, params: {
encrypted_payload: encrypted_payload,
message: message,
field_name: field_name,
error_message: error_message
}
expect(response).to have_http_status(:success)
expect(response).to render_template(:new)
end
it "sets react component props" do
get :new, params: {
encrypted_payload: encrypted_payload,
message: message,
field_name: field_name,
error_message: error_message
}
expect(assigns(:react_component_props)).to include(
message: message,
field_name: field_name,
error_message: error_message,
encrypted_payload: encrypted_payload,
form_action: secure_url_redirect_path
)
expect(assigns(:react_component_props)[:authenticity_token]).to be_present
end
it "uses default values when optional params are missing" do
get :new, params: {
encrypted_payload: encrypted_payload
}
expect(assigns(:react_component_props)).to include(
message: "Please enter the confirmation text to continue to your destination.",
field_name: "Confirmation text",
error_message: "Confirmation text does not match"
)
end
it "includes flash error in props when present" do
# Simulate a previous request that set flash error
request.session["flash"] = ActionDispatch::Flash::FlashHash.new
request.session["flash"]["error"] = "Test error message"
get :new, params: {
encrypted_payload: encrypted_payload
}
expect(assigns(:react_component_props)[:flash_error]).to eq("Test error message")
end
it "does not include flash_error in props when not present" do
get :new, params: {
encrypted_payload: encrypted_payload
}
expect(assigns(:react_component_props)).not_to have_key(:flash_error)
end
end
context "with missing required params" do
it "redirects to root when encrypted_payload is missing" do
get :new
expect(response).to redirect_to(root_path)
end
end
end
describe "POST #create" do
let(:valid_params) do
{
encrypted_payload: encrypted_payload,
confirmation_text: confirmation_text,
message: message,
field_name: field_name,
error_message: error_message
}
end
context "with valid confirmation text" do
it "redirects to the decrypted destination" do
post :create, params: valid_params
expect(response).to redirect_to(destination_url)
end
context "with send_confirmation_text parameter" do
let(:secure_payload_with_send_confirmation) do
{
destination: destination_url,
confirmation_texts: [confirmation_text],
created_at: Time.current.to_i,
send_confirmation_text: true
}
end
let(:encrypted_payload_with_send_confirmation) { SecureEncryptService.encrypt(secure_payload_with_send_confirmation.to_json) }
it "appends confirmation_text to destination URL when send_confirmation_text is true" do
params_with_send_confirmation = valid_params.merge(encrypted_payload: encrypted_payload_with_send_confirmation)
post :create, params: params_with_send_confirmation
expected_url = "#{destination_url.split('?').first}?confirmation_text=#{CGI.escape(confirmation_text)}&#{destination_url.split('?').last}"
expect(response).to redirect_to(expected_url)
end
it "does not append confirmation_text when send_confirmation_text is false or missing" do
post :create, params: valid_params
expect(response).to redirect_to(destination_url)
end
it "handles URLs that already have query parameters" do
destination_with_params = "#{destination_url}&existing=param"
secure_payload_with_params = {
destination: destination_with_params,
confirmation_texts: [confirmation_text],
created_at: Time.current.to_i,
send_confirmation_text: true
}
encrypted_payload_with_params = SecureEncryptService.encrypt(secure_payload_with_params.to_json)
params_with_send_confirmation = valid_params.merge(encrypted_payload: encrypted_payload_with_params)
post :create, params: params_with_send_confirmation
# The controller will reorganize parameters, so we need to check for the actual result
expect(response).to be_redirect
redirect_url = response.location
expect(redirect_url).to include("?confirmation_text=#{CGI.escape(confirmation_text)}")
expect(redirect_url).to include("&existing=param")
expect(redirect_url).to include("&email_type=notify")
end
end
end
context "with multiple confirmation texts" do
let(:confirmation_text_1) { "user1@example.com" }
let(:confirmation_text_2) { "user2@example.com" }
let(:confirmation_text_3) { "user3@example.com" }
let(:secure_payload_multiple) do
{
destination: destination_url,
confirmation_texts: [confirmation_text_1, confirmation_text_2, confirmation_text_3],
created_at: Time.current.to_i
}
end
let(:encrypted_payload_multiple) { SecureEncryptService.encrypt(secure_payload_multiple.to_json) }
it "accepts confirmation text that matches any of the allowed texts" do
post :create, params: valid_params.merge(
encrypted_payload: encrypted_payload_multiple,
confirmation_text: confirmation_text_3
)
expect(response).to redirect_to(destination_url)
end
it "rejects confirmation text that doesn't match any allowed text" do
post :create, params: valid_params.merge(
encrypted_payload: encrypted_payload_multiple,
confirmation_text: "nomatch@example.com"
)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => error_message })
end
it "works with single confirmation text (backward compatibility)" do
post :create, params: valid_params
expect(response).to redirect_to(destination_url)
end
context "with send_confirmation_text parameter" do
let(:secure_payload_multiple_with_send) do
{
destination: destination_url,
confirmation_texts: [confirmation_text_1, confirmation_text_2, confirmation_text_3],
created_at: Time.current.to_i,
send_confirmation_text: true
}
end
let(:encrypted_payload_multiple_with_send) { SecureEncryptService.encrypt(secure_payload_multiple_with_send.to_json) }
it "appends confirmation_text to destination URL when multiple texts are provided" do
post :create, params: valid_params.merge(
encrypted_payload: encrypted_payload_multiple_with_send,
confirmation_text: confirmation_text_2
)
expected_url = "#{destination_url.split('?').first}?confirmation_text=#{CGI.escape(confirmation_text_2)}&#{destination_url.split('?').last}"
expect(response).to redirect_to(expected_url)
end
end
end
context "with blank confirmation text" do
it "returns unprocessable entity with error message" do
post :create, params: valid_params.merge(confirmation_text: "")
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Please enter the confirmation text" })
end
it "returns unprocessable entity when confirmation text is nil" do
post :create, params: valid_params.except(:confirmation_text)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Please enter the confirmation text" })
end
it "returns unprocessable entity when confirmation text is whitespace only" do
post :create, params: valid_params.merge(confirmation_text: " ")
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Please enter the confirmation text" })
end
end
context "with incorrect confirmation text" do
it "returns unprocessable entity with custom error message" do
post :create, params: valid_params.merge(confirmation_text: "wrong@example.com")
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => error_message })
end
it "uses default error message when not provided" do
params_without_error_message = valid_params.except(:error_message).merge(confirmation_text: "wrong@example.com")
post :create, params: params_without_error_message
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Confirmation text does not match" })
end
end
context "with tampered encrypted data" do
it "returns unprocessable entity when encrypted_payload is tampered" do
tampered_encrypted = encrypted_payload + "tamper"
post :create, params: valid_params.merge(encrypted_payload: tampered_encrypted)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Invalid request" })
end
it "returns unprocessable entity when encrypted_payload is invalid JSON" do
invalid_payload = SecureEncryptService.encrypt("invalid json")
post :create, params: valid_params.merge(encrypted_payload: invalid_payload)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Invalid request" })
end
end
context "with expired payload" do
let(:expired_secure_payload) do
{
destination: destination_url,
confirmation_texts: [confirmation_text],
created_at: (Time.current - 25.hours).to_i
}
end
let(:expired_encrypted_payload) { SecureEncryptService.encrypt(expired_secure_payload.to_json) }
it "returns unprocessable entity when payload is expired" do
post :create, params: valid_params.merge(encrypted_payload: expired_encrypted_payload)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "This link has expired" })
end
end
context "with missing required params" do
it "redirects to root when encrypted_payload is missing" do
post :create, params: valid_params.except(:encrypted_payload)
expect(response).to redirect_to(root_path)
end
end
context "when destination is empty" do
let(:empty_destination_payload) do
{
destination: "",
confirmation_texts: [confirmation_text],
created_at: Time.current.to_i
}
end
let(:empty_destination_encrypted_payload) { SecureEncryptService.encrypt(empty_destination_payload.to_json) }
it "returns unprocessable entity with invalid destination error" do
post :create, params: valid_params.merge(encrypted_payload: empty_destination_encrypted_payload)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq({ "error" => "Invalid destination" })
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/embedded_javascripts_controller_spec.rb | spec/controllers/embedded_javascripts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe EmbeddedJavascriptsController do
render_views
describe "overlay" do
it "returns the correct js" do
get :overlay, format: :js
expect(response.body).to match(ActionController::Base.helpers.asset_url(Shakapacker.manifest.lookup!("overlay.js")))
expect(response.body).to match(ActionController::Base.helpers.stylesheet_pack_tag("overlay.css", protocol: PROTOCOL, host: DOMAIN))
end
end
describe "embed" do
it "returns the correct js" do
get :embed, format: :js
expect(response.body).to match(Shakapacker.manifest.lookup!("embed.js"))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/offer_codes_controller_spec.rb | spec/controllers/offer_codes_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe OfferCodesController do
describe "#compute_discount" do
let(:product) { create(:product, price_cents: 500) }
let(:offer_code) { create(:offer_code, products: [product], max_purchase_count: 2) }
let(:offer_code_params) do
{
code: offer_code.code,
products: {
product.unique_permalink => {
permalink: product.unique_permalink,
quantity: 2
}
}
}
end
it "returns an error in response when offer code is invalid" do
offer_code_params[:code] = "invalid_offer"
get :compute_discount, params: offer_code_params
expect(response.parsed_body).to eq({ "error_message" => "Sorry, the discount code you wish to use is invalid.", "error_code" => "invalid_offer", "valid" => false })
end
it "returns sold_out error in response when offer code is sold out" do
offer_code.update_attribute(:max_purchase_count, 0)
get :compute_discount, params: offer_code_params
expect(response.parsed_body).to eq({ "error_message" => "Sorry, the discount code you wish to use has expired.", "error_code" => "sold_out", "valid" => false })
end
it "doesn't return error in response when offer code discount is greater than the original price of the product but applicable to other product in a bundle" do
offer_code_amount = product.price_cents + 100
other_product = create(:product, price_cents: offer_code_amount, user: product.user)
universal_code = create(:universal_offer_code, amount_cents: offer_code_amount, user: product.user)
offer_code_params = {
code: universal_code.code,
products: {
other_product.unique_permalink => {
permalink: other_product.unique_permalink,
quantity: 2
}
}
}
get :compute_discount, params: offer_code_params
expect(response.parsed_body).to eq({
"valid" => true,
"products_data" => {
other_product.unique_permalink => {
"cents" => 600,
"type" => "fixed",
"product_ids" => nil,
"minimum_quantity" => nil,
"expires_at" => nil,
"duration_in_billing_cycles" => nil,
"minimum_amount_cents" => nil,
},
},
})
end
it "returns products data" do
get :compute_discount, params: offer_code_params
expect(response.parsed_body).to eq({
"valid" => true,
"products_data" => {
product.unique_permalink => {
"type" => "fixed",
"cents" => offer_code.amount,
"product_ids" => [product.external_id],
"minimum_quantity" => nil,
"expires_at" => nil,
"duration_in_billing_cycles" => nil,
"minimum_amount_cents" => nil,
},
},
})
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/licenses_controller_spec.rb | spec/controllers/licenses_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe LicensesController do
it_behaves_like "inherits from Sellers::BaseController"
render_views
let(:seller) { create(:named_seller) }
let(:license) { create(:license) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Audience::PurchasePolicy do
let(:record) { license.purchase }
let(:policy_method) { :manage_license? }
let(:request_params) { { id: license.external_id } }
end
describe "PUT update" do
it "updates the enabled status of the license" do
expect(license.disabled_at).to be_nil
put :update, format: :json, params: { id: license.external_id, enabled: false }
expect(response).to be_successful
expect(license.reload.disabled_at).to_not be_nil
put :update, format: :json, params: { id: license.external_id, enabled: true }
expect(response).to be_successful
expect(license.reload.disabled_at).to be_nil
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/healthcheck_controller_spec.rb | spec/controllers/healthcheck_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HealthcheckController do
describe "GET 'index'" do
it "returns 'healthcheck' as text" do
get :index
expect(response.status).to eq(200)
expect(response.body).to eq("healthcheck")
end
end
shared_examples "sidekiq healthcheck" do |queue_type, queue_name, limit|
context "#{queue_type} queues" do
before do
if queue_name.nil?
allow(queue_class).to receive(:new).and_return(queue_double)
else
allow(queue_class).to receive(:new).with(queue_name).and_return(queue_double)
end
end
let(:queue_double) { double("#{queue_type} double") }
it "returns HTTP success when the jobs count is under limit" do
allow(queue_double).to receive(:size).and_return(limit - 1)
get :sidekiq
expect(response.status).to eq(200)
expect(response.body).to eq("Sidekiq: ok")
end
it "returns HTTP service_unavailable when the jobs count is over the limit" do
allow(queue_double).to receive(:size).and_return(limit + 1)
get :sidekiq
expect(response.status).to eq(503)
expect(response.body).to eq("Sidekiq: service_unavailable")
end
end
end
describe "GET 'sidekiq'" do
describe "Sidekiq queues" do
it_behaves_like "sidekiq healthcheck", :queue, :critical, 12_000 do
let(:queue_class) { Sidekiq::Queue }
end
end
describe "Sidekiq retry set" do
it_behaves_like "sidekiq healthcheck", :retry_set, nil, 20_000 do
let(:queue_class) { Sidekiq::RetrySet }
end
end
describe "Sidekiq dead set" do
it_behaves_like "sidekiq healthcheck", :retry_set, nil, 10_000 do
let(:queue_class) { Sidekiq::DeadSet }
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/signup_controller_spec.rb | spec/controllers/signup_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "inertia_rails/rspec"
describe SignupController, type: :controller, inertia: true do
render_views
before :each do
request.env["devise.mapping"] = Devise.mappings[:user]
end
describe "GET new" do
describe "Sign up and connect to OAuth app" do
before do
@oauth_application = create(:oauth_application_valid)
@next_url = oauth_authorization_path(client_id: @oauth_application.uid, redirect_uri: @oauth_application.redirect_uri, scope: "edit_products")
end
it "returns the page successfully, sets the props correctly and sets noindex header" do
get :new, params: { next: @next_url }
expect(response).to be_successful
expect(assigns[:application]).to eq @oauth_application
expect(inertia.component).to eq("Signup/New")
expect(inertia.props[:email]).to be_nil
expect(inertia.props[:application_name]).to eq(@oauth_application.name)
expect(inertia.props[:recaptcha_site_key]).to eq(GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY"))
expect(response.headers["X-Robots-Tag"]).to eq "noindex"
end
def signup_props
referrer = User.find_by_username(params[:referrer]) if params[:referrer].present?
number_of_creators, total_made = $redis.mget(RedisKey.number_of_creators, RedisKey.total_made)
login_props.merge(
recaptcha_site_key: GlobalConfig.get("RECAPTCHA_SIGNUP_SITE_KEY"),
referrer: referrer ? {
id: referrer.external_id,
name: referrer.name_or_username,
} : nil,
stats: {
number_of_creators: number_of_creators.to_i,
total_made: total_made.to_i,
},
)
end
context "when an email is provided in the params" do
it "sets the email in the props" do
get :new, params: { email: "test@example.com" }
expect(inertia.props[:email]).to eq "test@example.com"
end
end
context "when an email is present in the next parameter" do
it "sets the email in the props" do
get :new, params: { next: settings_team_invitations_path(email: "test@example.com", format: :json) }
expect(inertia.props[:email]).to eq "test@example.com"
end
end
context "when a referrer is provided in the params" do
let(:referrer) { create(:user, username: "testreferrer") }
it "sets the referrer in the props" do
get :new, params: { referrer: referrer.username }
expect(inertia.props[:referrer]).to eq({
id: referrer.external_id,
name: referrer.name_or_username,
})
end
end
context "when stats are present in Redis" do
before do
$redis.mset(RedisKey.number_of_creators, 100, RedisKey.total_made, 1000000)
end
after do
$redis.del(RedisKey.number_of_creators)
$redis.del(RedisKey.total_made)
end
it "sets the stats in the props" do
get :new
expect(inertia.props[:stats]).to eq({
number_of_creators: 100,
total_made: 1000000,
})
end
end
context "when next param does not start with /oauth/authorize" do
it "sets noindex header" do
get :new, params: { next: "invalid-url" }
expect(response.headers["X-Robots-Tag"]).to be_nil
end
end
end
end
describe "POST create", :vcr do
describe "user already exists" do
before do
@user = create(:user, password: "password")
end
context "when two factor authentication is disabled for the user" do
it "signs in as user" do
post "create", params: { user: { email: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
expect(controller.user_signed_in?).to eq true
end
it "returns json response" do
post "create", params: { user: { email: @user.email, password: "password" } }, format: :json
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["redirect_location"]).to eq(dashboard_path)
end
end
context "when two factor authentication is enabled for the user" do
before do
@user.two_factor_authentication_enabled = true
@user.save!
end
it "sets the user_id in session and redirects for two factor authentication" do
post "create", params: { user: { email: @user.email, password: "password" } }
expect(session[:verify_two_factor_auth_for]).to eq @user.id
expect(response).to redirect_to(two_factor_authentication_path(next: dashboard_path))
expect(controller.user_signed_in?).to eq false
end
end
end
it "creates a user" do
user = build(:user, password: "password")
post "create", params: { user: { email: user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
last_user = User.last
expect(last_user.email).to eq user.email
last_user.valid_password?("password")
expect(last_user.confirmed?).to be(false)
expect(last_user.check_merchant_account_is_linked).to be(false)
end
it "creates a user and returns json response" do
user = build(:user, password: "password")
post "create", params: { user: { email: user.email, password: "password" } }, format: :json
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["redirect_location"]).to eq(dashboard_path)
end
it "sets two factor authenticated" do
expect(controller).to receive(:remember_two_factor_auth).and_call_original
user = build(:user, password: "password")
post :create, params: { user: { email: user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
end
describe "Sign up and connect to OAuth app" do
before do
@user = build(:user, password: "password")
oauth_application = create(:oauth_application_valid)
@next_url = oauth_authorization_path(client_id: oauth_application.uid, redirect_uri: oauth_application.redirect_uri, scope: "edit_products")
end
it "redirects to the OAuth authorization path after successful login" do
post "create", params: { user: { email: @user.email, password: "password" }, next: @next_url }
expect(response).to redirect_to(CGI.unescape(@next_url))
end
end
describe "tos agreement" do
describe "signup on a page that displayed the terms notice" do
let(:params) do
{
user: {
email: generate(:email),
password: "password",
terms_accepted: true
}
}
end
it "saves a tos agreement record for the user with their IP" do
@request.remote_ip = "192.168.0.1"
post("create", params:)
user = User.last
expect(user.tos_agreements.count).to eq(1)
expect(user.tos_agreements.last.ip).to eq("192.168.0.1")
end
end
describe "signup on a page that did not display the terms notice" do
let(:params) do
{
user: {
email: generate(:email),
password: "password"
}
}
end
it "does not save a tos agreement record for the user with their IP" do
post("create", params:)
user = User.last
expect(user.tos_agreements.count).to eq(0)
end
end
end
it "creates a global affiliate record" do
user = build(:user, password: "password")
post "create", params: { user: { email: user.email, password: "password" } }
user = User.last
expect(user.global_affiliate).to be_present
end
it "saves the user even when a payment made with a transient client token is expired" do
allow_any_instance_of(CardParamsHelper).to receive(:build_chargeable).and_raise(ChargeProcessorInvalidRequestError)
user = build(:user, password: "password")
expect do
post "create", params: { user: { email: user.email, password: "password" } }
end.to change { User.count }.by(1)
last_user = User.last
expect(last_user.email).to eq user.email
last_user.valid_password?("password")
expect(last_user.confirmed?).to be(false)
end
it "does not create user if user payload is not given" do
post "create"
expect(response).to redirect_to(signup_path)
expect(flash[:warning]).to eq "Please provide a valid email address."
end
it "returns json error if user payload is not given" do
post "create", format: :json
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq "Please provide a valid email address."
end
it "turns notifications off the user if the user is from Canada" do
@request.env["REMOTE_ADDR"] = "76.66.210.142"
user = build(:user, password: "password")
post "create", params: { user: { email: user.email, password: "password" } }
last_user = User.last
expect(last_user.announcement_notification_enabled).to eq false
end
it "creates a signup event" do
@request.remote_ip = "12.12.128.128"
user = build(:user, password: "password")
post "create", params: { user: { email: user.email, password: "password" } }
new_user = User.find_by(email: user.email)
expect(SignupEvent.last.user_id).to eq new_user.id
expect(SignupEvent.last.ip_address).to eq "12.12.128.128"
end
it "saves the account created ip" do
@request.remote_ip = "12.12.128.128"
@user = build(:user, password: "password")
post "create", params: { user: { email: @user.email, password: "password" } }
expect(User.last.account_created_ip).to eq "12.12.128.128"
end
it "doesn't redirect externally and deals with badly-formed referer URLs" do
purchase = create(:purchase)
referrer_path = "?__utma=11926824.84037407.1424232314.1424240345.1425108120.4"
referrer_path += "&__utmb=11926824.3.9.1425108369109&__utmc=11926824&__utmx=-&__utmz=11926824.1425108120.4.4.utmcsr=english_blog|"
referrer_path += "utmccn=msr2015_companion|utmcmd=banner|utmcct=in_300x600_banner_ad&__utmv=-&__utmk=223657947"
referrer_url = [request.protocol, "badguy.com", referrer_path].join
request.headers["HTTP_REFERER"] = referrer_url
expect do
post :create, params: { user:
{ email: purchase.email, add_purchase_to_existing_account: false, buyer_signup: true, password: "password", purchase_id: purchase.external_id } }
expect(response).to redirect_to(Addressable::URI.escape(referrer_path))
end.to change { User.count }.by(1)
end
describe "invites" do
describe "external_id" do
before do
@user = create(:user)
create(:invite, sender_id: @user.id, receiver_email: "anish@gumroad.com")
end
it "updates invite to signed up and save receiver_id" do
expect(Invite.last.invite_state).to eq "invitation_sent"
post "create", params: { user: { email: "anish@gumroad.com", password: "password" }, referral: @user.external_id }
expect(Invite.last.invite_state).to eq "signed_up"
expect(Invite.last.receiver_id).to eq User.last.id
end
it "creates a new invite and make it signed up with receiver_id" do
expect { post "create", params: { user: { email: "anish+2@gumroad.com", password: "password" }, referral: @user.external_id } }.to change {
Invite.count
}.by(1)
expect(Invite.last.sender_id).to eq @user.id
expect(Invite.last.invite_state).to eq "signed_up"
expect(Invite.last.receiver_email).to eq "anish+2@gumroad.com"
expect(Invite.last.receiver_id).to eq User.last.id
end
it "does not create a new invite" do
expect { post "create", params: { user: { email: "anish@gumroad.com", password: "password" } } }.to change {
Invite.count
}.by(0)
end
it "does not change any existing invites" do
expect(Invite.last.invite_state).to eq "invitation_sent"
post "create", params: { user: { email: "anish@gumroad.com", password: "password" } }
expect(Invite.last.invite_state).to eq "invitation_sent"
expect(Invite.last.receiver_id).to be(nil)
end
end
end
it "links user purchase and credit card", :vcr do
# Provided a credit card and purchase made, a user that signs up for a
# buyer side account will be linked to these other models.
# Signup with CC is without CVC because it's done automatically in the background when user enters a password
# after having completed a purchase (that clears the CVC).
card_data = StripePaymentMethodHelper.success.without(:cvc)
purchase = create(:purchase, stripe_fingerprint: card_data.to_stripejs_fingerprint)
params = card_data.to_stripejs_params.merge!(purchase_id: ObfuscateIds.encrypt(purchase.id))
user = build(:user, password: "password")
# Ensure purchase and card are not linked to it at this point
expect(user.purchases).to be_empty
expect(user.credit_card).to be(nil)
user_params = { email: user.email, password: "password" }
user_params.update(params)
post "create", params: { user: user_params }
last_user = User.last
expect(last_user.email).to eq user.email
expect(last_user.purchases.first.id).to eq purchase.id
expect(last_user.credit_card.id).to_not be(nil)
expect(last_user.credit_card.expiry_month).to eq 12
expect(last_user.credit_card.expiry_year).to eq 2023
end
it "links user purchase but not credit card if fingerprint different to purchase credit card", :vcr do
# Provided a credit card and purchase made, a user that signs up for a
# buyer side account will be linked to these other models.
# Signup with CC is without CVC because it's done automatically in the background when user enters a password
# after having completed a purchase (that clears the CVC).
# To limit risk, we only accept the CC number on signup, if it's with a purchase
# that the CC has been used on.
card_data = StripePaymentMethodHelper.success.without(:cvc)
purchase = create(:purchase, stripe_fingerprint: "some-other-finger-print")
params = card_data.to_stripejs_params.merge!(purchase_id: ObfuscateIds.encrypt(purchase.id))
user = build(:user, password: "password")
# Ensure purchase and card are not linked to it at this point
expect(user.purchases).to be_empty
expect(user.credit_card).to be(nil)
user_params = { email: user.email, password: "password" }
user_params.update(params)
post "create", params: { user: user_params }
last_user = User.last
expect(last_user.email).to eq user.email
expect(last_user.purchases.first.id).to eq purchase.id
expect(last_user.credit_card).to be(nil)
end
it "links past purchases by email if they're not linked to purchasers already" do
user = build(:user, password: "password")
purchase = create(:purchase, email: user.email)
create(:purchase, email: user.email, purchaser: create(:user))
expect(user.purchases).to be_empty
post "create", params: { user: { email: user.email, password: "password" } }
last_user = User.last
expect(last_user.email).to eq user.email
expect(last_user.purchases.count).to eq 1
expect(last_user.purchases.first.id).to eq purchase.id
end
it "associates the preorder with the newly created user", :vcr do
purchase = create(:purchase)
preorder = create(:preorder)
purchase.preorder = preorder
purchase.save
params = StripePaymentMethodHelper.success.to_stripejs_params.merge!(purchase_id: ObfuscateIds.encrypt(purchase.id))
user = build(:user, password: "password")
user_params = { email: user.email, password: "password" }
user_params.update(params)
post "create", params: { user: user_params }
new_user = User.last
expect(new_user.preorders_bought).to eq [preorder]
end
end
describe "POST 'save_to_library'" do
describe "email already taken" do
before do
@user = create(:user)
@purchase = create(:purchase)
@url_redirect = create(:url_redirect, purchase: @purchase)
end
it "failed and has email taken error" do
post :save_to_library, params: { user: { email: @user.email, password: "blah123", purchase_id: @purchase.external_id } }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq "An account already exists with this email.".html_safe
end
end
describe "email not yet taken" do
before do
@purchase = create(:purchase)
end
it "signs up the user" do
post :save_to_library, params: { user: { email: @purchase.email, password: "blah123", purchase_id: @purchase.external_id } }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["error_message"]).to be(nil)
user = User.last
expect(user.email).to eq @purchase.email
end
it "assigns them the correct purchase" do
expect { post :save_to_library, params: { user: { email: @purchase.email, password: "blah123", purchase_id: @purchase.external_id } } }
.to change { @purchase.reload.purchaser.nil? }.from(true).to(false)
end
it "fails because password too short" do
post :save_to_library, params: { user: { email: @purchase.email, password: "bla", purchase_id: @purchase.external_id } }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq "Password is too short (minimum is 4 characters)"
end
it "redirects to the library" do
post :save_to_library, params: { user: { email: @purchase.email, password: "blah123", purchase_id: @purchase.external_id } }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["error_message"]).to be(nil)
end
it "associates past purchases with the same email to the new user" do
purchase1 = create(:purchase, email: @purchase.email)
purchase2 = create(:purchase, email: @purchase.email)
expect(purchase1.purchaser_id).to be_nil
expect(purchase2.purchaser_id).to be_nil
post :save_to_library, params: { user: { email: @purchase.email, password: "blah123", purchase_id: @purchase.external_id } }
expect(response).to be_successful
user = User.last
[@purchase, purchase1, purchase2].each do |purchase|
expect(purchase.reload.purchaser_id).to eq(user.id)
end
end
it "creates a global affiliate record" do
post :save_to_library, params: { user: { email: @purchase.email, password: "blah123", purchase_id: @purchase.external_id } }
user = User.last
expect(user.global_affiliate).to be_present
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/test_pings_controller_spec.rb | spec/controllers/test_pings_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe TestPingsController do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:user, notification_endpoint: "http://notification.com") }
let(:product) { create(:product, user: seller) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for action", :post, :create do
let(:record) { seller }
let(:policy_klass) { Settings::Advanced::UserPolicy }
let(:policy_method) { :test_ping? }
end
describe "POST create" do
it "posts a test ping containing latest sale details to the specified endpoint" do
create(:purchase, link: product, created_at: 2.days.ago)
create(:purchase, link: product)
last_purchase = create(:purchase, link: product, created_at: 2.hours.from_now)
ping_url = last_purchase.seller.notification_endpoint
ping_params = last_purchase.payload_for_ping_notification
http_double = double
expect(HTTParty).to receive(:post).with(ping_url,
timeout: 5,
body: ping_params.merge(test: true).deep_stringify_keys,
headers: { "Content-Type" => last_purchase.seller.notification_content_type })
.and_return(http_double)
post :create, params: { url: ping_url }
expect(response.body).to include "Your last sale's data has been sent to your Ping URL."
end
it "fails and displays error if no sale present for the user" do
expect(HTTParty).not_to receive(:post)
post :create, params: { url: product.user.notification_endpoint }
expect(response.body).to include "There are no sales on your account to test with. Please make a test purchase and try again."
end
it "fails and displays error if invalid URL is passed" do
expect(HTTParty).not_to receive(:post)
post :create, params: { url: "not_a_url" }
expect(response.body).to include "That URL seems to be invalid."
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/posts_controller_spec.rb | spec/controllers/posts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe PostsController do
let(:seller) { create(:named_seller) }
context "within seller area" do
include_context "with user signed in as admin for seller"
describe "GET redirect_from_purchase_id" do
before do
@product = create(:product, user: seller)
@purchase = create(:purchase, link: @product)
end
let(:installment) { create(:published_installment, link: @product, installment_type: "product", shown_on_profile: false) }
it_behaves_like "authorize called for action", :get, :redirect_from_purchase_id do
let(:record) { Installment }
let(:request_params) { { id: installment.external_id, purchase_id: @purchase.external_id } }
end
it "redirects old /library/purchase/purchase_id paths to the new path" do
get :redirect_from_purchase_id, params: { id: installment.external_id, purchase_id: @purchase.external_id }
expect(response).to redirect_to(view_post_path(
username: installment.user.username.presence || installment.user.external_id,
slug: installment.slug,
purchase_id: @purchase.external_id))
end
end
describe "GET send_for_purchase" do
before do
link = create(:product, user: seller)
@post = create(:installment, link:)
@purchase = create(:purchase, seller:, link:, created_at: Time.current)
create(:creator_contacting_customers_email_info_delivered, installment: @post, purchase: @purchase)
end
before do
create(:payment_completed, user: seller)
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(Installment::MINIMUM_SALES_CENTS_VALUE)
end
it_behaves_like "authorize called for action", :get, :send_for_purchase do
let(:record) { Installment }
let(:request_params) { { id: @post.external_id, purchase_id: @purchase.external_id } }
end
it "returns an error if 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)
@purchase.create_url_redirect!
expect(PostSendgridApi).to_not receive(:process)
get :send_for_purchase, params: { id: @post.external_id, purchase_id: @purchase.external_id }
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body).to eq("message" => "You are not eligible to resend this email.")
end
it "returns 404 if no purchase" do
expect(PostSendgridApi).to_not receive(:process)
expect do
get :send_for_purchase, params: { id: @post.external_id, purchase_id: "hello" }
end.to raise_error(ActiveRecord::RecordNotFound)
end
it "returns success and redelivers the installment" do
@purchase.create_url_redirect!
expect(PostSendgridApi).to receive(:process).with(
post: @post,
recipients: [{
email: @purchase.email,
purchase: @purchase,
url_redirect: @purchase.url_redirect,
}]
)
get :send_for_purchase, params: { id: @post.external_id, purchase_id: @purchase.external_id }
expect(response).to be_successful
expect(response).to have_http_status(:no_content)
# when the purchase part of a subscription
membership_purchase = create(:membership_purchase, link: create(:membership_product, user: @post.seller))
membership_purchase.create_url_redirect!
expect(PostSendgridApi).to receive(:process).with(
post: @post,
recipients: [{
email: membership_purchase.email,
purchase: membership_purchase,
url_redirect: membership_purchase.url_redirect,
subscription: membership_purchase.subscription,
}]
)
get :send_for_purchase, params: { id: @post.external_id, purchase_id: membership_purchase.external_id }
expect(response).to be_successful
expect(response).to have_http_status(:no_content)
end
end
end
context "within consumer area" do
before do
sign_in seller
end
describe "GET 'show'" do
before do
@user = create(:named_user)
@product = create(:product, user: @user)
@purchase = create(:purchase, link: @product)
@request.host = URI.parse(@user.subdomain_with_protocol).host
end
it "renders a non-public product installment with a valid purchase_id" do
installment = create(:published_installment, link: @product, installment_type: "product", shown_on_profile: false)
get :show, params: { username: @user.username, slug: installment.slug, purchase_id: @purchase.external_id }
expect(response).to be_successful
end
it "sets @on_posts_page instance variable to make nav item active" do
installment = create(:published_installment, link: @product, installment_type: "product", shown_on_profile: false)
get :show, params: { username: @user.username, slug: installment.slug, purchase_id: @purchase.external_id }
expect(assigns(:on_posts_page)).to eq(true)
end
it "sets @user instance variable to load third-party analytics config" do
installment = create(:published_installment, link: @product, installment_type: "product", shown_on_profile: false)
get :show, params: { username: @user.username, slug: installment.slug, purchase_id: @purchase.external_id }
expect(assigns[:user]).to eq installment.seller
end
context "with user signed in as support for seller" do
include_context "with user signed in as support for seller"
let(:product) { create(:product, user: seller) }
let(:post) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) }
it "renders post" do
get :show, params: { username: seller.username, slug: post.slug }
expect(response).to be_successful
end
end
it "renders a publicly visible installment even if it doesn't have a purchase_id" do
installment = create(:published_installment, installment_type: Installment::AUDIENCE_TYPE, seller: @user, shown_on_profile: true)
get :show, params: { username: @user.username, slug: installment.slug }
expect(response).to be_successful
end
it "does not render a non-public installment if it doesn't have a valid purchase_id" do
installment = create(:published_installment, seller: @user, shown_on_profile: false)
expect { get :show, params: { username: @user.username, slug: installment.slug } }.to raise_error(ActionController::RoutingError)
end
it "does not render a non-published installment" do
installment = create(:installment, seller: @user, shown_on_profile: true)
expect { get :show, params: { username: @user.username, slug: installment.slug } }.to raise_error(ActionController::RoutingError)
end
it "does not render a deleted published installment" do
installment = create(:published_installment, seller: @user, shown_on_profile: true, deleted_at: Time.current)
expect { get :show, params: { username: @user.username, slug: installment.slug } }.to raise_error(ActionController::RoutingError)
end
it "raises routing error if slug is invalid" do
expect { get :show, params: { username: @user.username, slug: "invalid_slug" } }.to raise_error(ActionController::RoutingError)
end
it "does not show posts for suspended users" do
admin_user = create(:admin_user)
installment = create(:published_installment, seller: @user, shown_on_profile: true)
@user.flag_for_fraud!(author_id: admin_user.id)
@user.suspend_for_fraud!(author_id: admin_user.id)
expect { get :show, params: { username: @user.username, slug: installment.slug } }.to raise_error(ActionController::RoutingError)
user = create(:user)
installment = create(:audience_installment, seller: user, shown_on_profile: true, published_at: Time.current)
user.flag_for_fraud!(author_id: admin_user.id)
user.suspend_for_fraud!(author_id: admin_user.id)
expect { get :show, params: { username: user.username, slug: installment.slug } }.to raise_error(ActionController::RoutingError)
end
context "when requested through custom domain" do
before do
create(:custom_domain, user: @user, domain: "example.com")
@post = create(:published_installment, installment_type: Installment::AUDIENCE_TYPE, seller: @user, shown_on_profile: true)
@request.host = "example.com"
end
it "renders the post" do
get :show, params: { slug: @post.slug }
expect(assigns[:post]).to eq @post
expect(response).to be_successful
end
end
context "when requested through app domain" do
before do
@request.host = DOMAIN
@post = create(:published_installment, installment_type: Installment::AUDIENCE_TYPE, seller: @user, shown_on_profile: true)
end
it "redirects to subdomain url of the post" do
get :show, params: { username: @user.username, slug: @post.slug, purchase_id: 123 }
expect(request).to redirect_to custom_domain_view_post_url(slug: @post.slug, host: @user.subdomain_with_protocol, purchase_id: 123)
expect(response).to have_http_status(:moved_permanently)
end
end
end
describe "increment_post_views" do
describe "page view incrementor" do
it "increments the post page view with a new Event and InstallmentEvent record" do
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.165 Safari/535.19"
@request.env["HTTP_USER_AGENT"] = user_agent
installment = create(:installment, name: "installment")
post :increment_post_views, params: { id: installment.external_id }
post_view_event = Event.post_view.last
installment_event = InstallmentEvent.last
expect(installment_event.installment_id).to be(installment.id)
expect(installment_event.event_id).to be(post_view_event.id)
end
it "creates a post page view event associated with a link" do
link = create(:product)
installment = create(:installment, link:, installment_type: "product")
post :increment_post_views, params: { id: installment.external_id, parent_referrer: "t.co/9ew9j9" }
post_view_event = Event.post_view.last
expect(post_view_event.parent_referrer).to eq "t.co/9ew9j9"
expect(post_view_event.link_id).to eq link.id
end
it "increments the page view for other user" do
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.165 Safari/535.19"
@request.env["HTTP_USER_AGENT"] = user_agent
create(:user)
another_user = create(:user)
sign_in another_user
installment = create(:installment)
post :increment_post_views, params: { id: installment.external_id }
post_view_event = Event.post_view.last
expect(post_view_event.user_id).to eq another_user.id
end
it "increments the page view if user is anonymous" do
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.165 Safari/535.19"
@request.env["HTTP_USER_AGENT"] = user_agent
create(:user)
sign_out seller
installment = create(:installment)
post :increment_post_views, params: { id: installment.external_id }
post_view_event = Event.post_view.last
installment_event = InstallmentEvent.last
expect(installment_event.installment_id).to be(installment.id)
expect(installment_event.event_id).to be(post_view_event.id)
end
it "does not increment page views for bots" do
@request.env["HTTP_USER_AGENT"] = "EventMachine HttpClient"
installment = create(:installment)
post :increment_post_views, params: { id: installment.external_id }
expect(Event.post_view.count).to be(0)
end
it "does not increment page views for same user" do
user = create(:user)
installment = create(:installment, seller: user)
allow(controller).to receive(:current_user).and_return(user)
post :increment_post_views, params: { id: installment.external_id }
expect(Event.post_view.count).to be(0)
end
it "does not increment page views for admin user" do
user = create(:admin_user)
allow(controller).to receive(:current_user).and_return(user)
installment = create(:installment)
post :increment_post_views, params: { id: installment.external_id }
expect(Event.post_view.count).to be(0)
end
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
it "does not increment page views for team member" do
# user = create(:admin_user)
# allow(controller).to receive(:current_user).and_return(user)
installment = create(:installment, seller:)
post :increment_post_views, params: { id: installment.external_id }
expect(Event.post_view.count).to be(0)
end
end
it "does not increment page views for bots that pretends to be same user" do
user = create(:user)
allow(controller).to receive(:current_user).and_return(user)
create(:product, user:)
@request.env["HTTP_USER_AGENT"] = "EventMachine HttpClient"
installment = create(:installment)
post :increment_post_views, params: { id: installment.external_id }
expect(Event.post_view.count).to be(0)
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/controllers/workflows_controller_spec.rb | spec/controllers/workflows_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/sellers_base_controller_concern"
require "inertia_rails/rspec"
describe WorkflowsController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:user) }
let(:workflow) { create(:workflow, seller: seller) }
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Workflow }
end
it "renders successfully with Inertia" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Workflows/Index")
expect(inertia.props[:workflows]).to be_an(Array)
end
end
describe "GET new" do
it_behaves_like "authorize called for action", :get, :new do
let(:record) { Workflow }
end
it "renders successfully with Inertia" do
get :new
expect(response).to be_successful
expect(inertia).to render_component("Workflows/New")
expect(inertia.props[:context]).to be_present
end
end
describe "GET edit" do
it_behaves_like "authorize called for action", :get, :edit do
let(:record) { workflow }
let(:request_params) { { id: workflow.external_id } }
end
it "renders successfully with Inertia" do
get :edit, params: { id: workflow.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Workflows/Edit")
expect(inertia.props[:workflow]).to be_present
expect(inertia.props[:context]).to be_present
end
context "when workflow doesn't exist" do
it "returns 404" do
expect { get :edit, params: { id: "nonexistent" } }.to raise_error(ActionController::RoutingError)
end
end
end
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:record) { Workflow }
let(:request_params) { { workflow: { name: "Test Workflow", workflow_type: "audience" } } }
end
context "with valid params" do
it "303 redirects to workflow emails page with a success message" do
post :create, params: { workflow: { name: "Test Workflow", workflow_type: "audience" } }
expect(response).to redirect_to(workflow_emails_path(Workflow.last.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq("Changes saved!")
end
end
context "with invalid params" do
it "redirects back to new workflow page with errors when service fails" do
allow_any_instance_of(Workflow::ManageService).to receive(:process).and_return([false, "Name can't be blank"])
post :create, params: { workflow: { name: "", workflow_type: "audience" } }
expect(response).to redirect_to(new_workflow_path)
expect(response.status).to eq(302)
end
it "handles validation errors from the service" do
workflow_params = { name: "Test", workflow_type: "audience" }
service = instance_double(Workflow::ManageService)
allow(Workflow::ManageService).to receive(:new).and_return(service)
allow(service).to receive(:process).and_return([false, "Validation failed"])
post :create, params: { workflow: workflow_params }
expect(response).to redirect_to(new_workflow_path)
end
end
context "with abandoned cart workflow" do
it "returns error when seller is not eligible for abandoned cart workflows" do
allow_any_instance_of(User).to receive(:eligible_for_abandoned_cart_workflows?).and_return(false)
post :create, params: { workflow: { name: "Cart Workflow", workflow_type: "abandoned_cart" } }
expect(response).to redirect_to(new_workflow_path)
end
end
end
describe "PATCH update" do
it_behaves_like "authorize called for action", :patch, :update do
let(:record) { workflow }
let(:request_params) { { id: workflow.external_id, workflow: { name: "Updated Workflow" } } }
end
context "with valid params" do
it "303 redirects to workflow emails page with a success message" do
patch :update, params: { id: workflow.external_id, workflow: { name: "Updated Workflow" } }
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq("Changes saved!")
end
it "redirects to workflow emails page with publish message when save_and_publish" do
# Mark workflow as published previously so it can be published again
workflow.update_columns(first_published_at: 1.day.ago, published_at: nil)
# Ensure seller is eligible to send emails
allow_any_instance_of(User).to receive(:eligible_to_send_emails?).and_return(true)
patch :update, params: { id: workflow.external_id, workflow: { name: "Updated Workflow", save_action_name: "save_and_publish" } }
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq("Workflow published!")
end
it "redirects to workflow emails page with unpublish message when save_and_unpublish" do
patch :update, params: { id: workflow.external_id, workflow: { name: "Updated Workflow", save_action_name: "save_and_unpublish" } }
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq("Unpublished!")
end
end
context "with invalid params" do
it "redirects back to edit workflow page with errors when service fails" do
allow_any_instance_of(Workflow::ManageService).to receive(:process).and_return([false, "Name can't be blank"])
patch :update, params: { id: workflow.external_id, workflow: { name: "" } }
expect(response).to redirect_to(edit_workflow_path(workflow.external_id))
expect(flash[:alert]).to eq("Name can't be blank")
end
it "handles validation errors from the service" do
service = instance_double(Workflow::ManageService)
allow(Workflow::ManageService).to receive(:new).and_return(service)
allow(service).to receive(:process).and_return([false, "Validation failed"])
patch :update, params: { id: workflow.external_id, workflow: { name: "Test" } }
expect(response).to redirect_to(edit_workflow_path(workflow.external_id))
expect(flash[:alert]).to eq("Validation failed")
end
it "handles ActiveRecord::RecordInvalid errors" do
allow_any_instance_of(Workflow::ManageService).to receive(:process).and_raise(ActiveRecord::RecordInvalid.new(workflow))
expect do
patch :update, params: { id: workflow.external_id, workflow: { name: "Test" } }
end.to raise_error(ActiveRecord::RecordInvalid)
end
end
context "when workflow doesn't exist" do
it "returns 404" do
expect do
patch :update, params: { id: "nonexistent", workflow: { name: "Test" } }
end.to raise_error(ActionController::RoutingError)
end
end
end
describe "DELETE destroy" do
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { workflow }
let(:request_params) { { id: workflow.external_id } }
end
it "303 redirects to workflows page with a success message" do
delete :destroy, params: { id: workflow.external_id }
expect(response).to redirect_to(workflows_path)
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq("Workflow deleted!")
expect(workflow.reload.deleted_at).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/controllers/shipments_controller_spec.rb | spec/controllers/shipments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe ShipmentsController, :vcr do
describe "POST verify_shipping_address" do
describe "US address" do
before do
@params = {
street_address: "1640 17th St",
city: "San Francisco",
state: "CA",
zip_code: "94107",
country: "United States"
}
end
describe "valid address" do
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
it "returns correct response" do
post :verify_shipping_address, params: @params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["street_address"]).to eq "1640 17TH ST"
expect(response.parsed_body["city"]).to eq "SAN FRANCISCO"
expect(response.parsed_body["state"]).to eq "CA"
expect(response.parsed_body["zip_code"]).to eq "94107"
end
describe "valid address but with minor corrections" do
before do
@params.merge!(street_address: "1640 17 Street")
end
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
it "returns correct response" do
post :verify_shipping_address, params: @params
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["easypost_verification_required"]).to be(true)
expect(response.parsed_body["street_address"]).to eq "1640 17TH ST"
expect(response.parsed_body["city"]).to eq "SAN FRANCISCO"
expect(response.parsed_body["state"]).to eq "CA"
expect(response.parsed_body["zip_code"]).to eq "94107"
expect(response.parsed_body["formatted_address"]).to eq "1640 17th St, San Francisco, CA, 94107"
expect(response.parsed_body["formatted_original_address"]).to eq "1640 17 Street, San Francisco, CA, 94107"
end
end
end
describe "needs more information" do
before do
@params.merge!(street_address: "255 King Street")
end
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
end
describe "unverified address" do
before do
@params.merge!(street_address: "16400 17th Street")
end
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
it "returns needs more information response" do
post :verify_shipping_address, params: @params
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq "We are unable to verify your shipping address. Is your address correct?"
end
end
end
describe "international address" do
before do
@params = {
street_address: "9384 Cardston Ct",
city: "Burnaby",
state: "BC",
zip_code: "V3N 4H4",
country: "Canada"
}
end
describe "valid address" do
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
it "returns correct response" do
post :verify_shipping_address, params: @params
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["street_address"]).to eq "9384 CARDSTON CT"
expect(response.parsed_body["city"]).to eq "BURNABY"
expect(response.parsed_body["state"]).to eq "BC"
expect(response.parsed_body["zip_code"]).to eq "V3N 4H4"
end
end
describe "unverified address" do
before do
@params.merge!(street_address: "17th Street")
end
it "calls EasyPost" do
expect_any_instance_of(EasyPost::Services::Address).to receive(:create).and_call_original
post :verify_shipping_address, params: @params
end
it "returns needs more information response" do
post :verify_shipping_address, params: @params
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq "We are unable to verify your shipping address. Is your address correct?"
end
end
end
end
describe "POST mark_as_shipped" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller:) }
let(:purchase_with_shipment) { create(:purchase, link: product, seller:) }
let!(:shipment) { create(:shipment, purchase: purchase_with_shipment) }
let(:tracking_url) { "https://tools.usps.com/go/TrackConfirmAction?qtc_tLabels1=1234567890" }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for action", :post, :mark_as_shipped do
let(:record) { purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { purchase_id: purchase.external_id } }
end
it "no shipment exists - should mark a purchase as shipped" do
expect { post :mark_as_shipped, params: { purchase_id: purchase.external_id } }.to change { Shipment.count }.by(1)
expect(response).to be_successful
expect(purchase.shipment.shipped?).to be(true)
end
it "shipment exists - should mark a purchase as shipped" do
expect { post :mark_as_shipped, params: { purchase_id: purchase_with_shipment.external_id } }.to change { Shipment.count }.by(0)
expect(response).to be_successful
expect(shipment.reload.shipped?).to be(true)
end
describe "tracking information" do
it "no shipment exists - should mark a purchase as shipped" do
expect { post :mark_as_shipped, params: { purchase_id: purchase.external_id, tracking_url: } }.to change { Shipment.count }.by(1)
expect(response).to be_successful
expect(purchase.shipment.shipped?).to be(true)
expect(purchase.shipment.tracking_url).to eq(tracking_url)
end
it "shipment exists - should mark a purchase as shipped" do
expect { post :mark_as_shipped, params: { purchase_id: purchase_with_shipment.external_id, tracking_url: } }.to change { Shipment.count }.by(0)
expect(response).to be_successful
expect(shipment.reload.shipped?).to be(true)
expect(shipment.tracking_url).to eq(tracking_url)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/application_controller_spec.rb | spec/controllers/application_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe ApplicationController do
controller do
def index
render plain: "spec"
end
end
def index(p = {})
get :index, params: p
end
def stubbed_cookie
calculated_fingerprint = "3dfakl93klfdjsa09rn"
allow(controller).to receive(:params).and_return(plugins: "emptypluginstring",
friend: "fdkljafldkasjfkljasf")
allow(Digest::MD5).to receive(:hexdigest).and_return(calculated_fingerprint)
cookies[:_gumroad_guid] = "fdakjl9fdoakjs9"
end
describe "#invalidate_session_if_necessary" do
let!(:user) { create(:user, last_active_sessions_invalidated_at: 1.month.ago) }
it "does not invalidate session if user is not logged in via devise" do
index
expect(response).to be_successful
end
it "does not invalidate session if user is not logged in via devise and logged_in_user is present" do
allow(controller).to receive(:logged_in_user).and_return(user)
index
expect(response).to be_successful
end
it "invalidates session if user is logged in via devise and last_sign_in_at < last_active_sessions_invalidated_at" do
sign_in user
user.update!(last_active_sessions_invalidated_at: 1.day.from_now)
index
expect(response).to redirect_to(login_path)
end
end
describe "includes CustomDomainRouteBuilder" do
it { expect(ApplicationController.ancestors.include?(CustomDomainRouteBuilder)).to eq(true) }
end
describe "Event creation" do
it "sets the referrer from params if its provided" do
allow(controller).to receive(:params).and_return(referrer: "http://www.google.com")
event = controller.create_service_charge_event(create(:service_charge))
expect(event.referrer).to eq "http://www.google.com"
end
it "sets the referrer from params even if params is an array" do
allow(controller).to receive(:params).and_return(referrer: ["https://gumroad.com", "https://www.google.com"])
event = controller.create_service_charge_event(create(:service_charge))
expect(event.referrer).to eq "https://www.google.com"
end
it "sets the referrer from the request if it is not provided in the params" do
allow(controller).to receive(:params).and_return(referrer: nil)
expect(request).to receive(:referrer).and_return("http://www.yahoo.com")
event = controller.create_service_charge_event(create(:service_charge))
expect(event.referrer).to eq "http://www.yahoo.com"
end
context "with admin signed" do
let(:admin) { create(:admin_user) }
let(:user) { create(:user) }
before do
sign_in admin
end
context "with admin becoming user" do
before do
controller.impersonate_user(user)
end
it "does not return an event" do
stubbed_cookie
event = controller.create_user_event("service_charge")
expect(event).to be(nil)
end
end
context "without admin becoming user" do
it "returns an event" do
stubbed_cookie
event = controller.create_user_event("service_charge")
expect(event).to_not be(nil)
end
end
end
it "saves the browser_plugins and friend actions in extra_features" do
stubbed_cookie
event = controller.create_user_event("service_charge")
expect(event.extra_features[:browser_plugins]).to eq "emptypluginstring"
expect(event.extra_features[:friend_actions]).to eq "fdkljafldkasjfkljasf"
expect(event.extra_features[:browser]).to eq "Rails Testing"
expect(event).to_not be(nil)
end
it "survives being called with nil" do
event = controller.create_user_event(nil)
expect(event).to be_nil
end
it "creates a permitted event when not logged in" do
event = controller.create_user_event("first_purchase_on_profile_visit")
expect(event).to be_present
end
it "does not create a non-permitted event when not logged in" do
event = controller.create_user_event("unknown_event")
expect(event).to be_nil
end
it "creates a non-permitted event when logged in" do
allow(controller).to receive(:current_user).and_return(create(:user))
event = controller.create_user_event("unknown_event")
expect(event).to be_present
end
end
describe "custom host redirection" do
context "when the host is configured to redirect" do
before do
allow_any_instance_of(SubdomainRedirectorService).to receive(:redirects).and_return({ "live.gumroad.com" => "https://example.com" })
@request.host = "live.gumroad.com"
allow_any_instance_of(@request.class).to receive(:fullpath).and_return("/")
index
end
it "redirects to redirect_url" do
expect(response).to redirect_to("https://example.com")
end
end
context "when the host+fullpath is configured to redirect" do
before do
allow_any_instance_of(SubdomainRedirectorService).to receive(:redirects).and_return({ "live.gumroad.com/123" => "https://example.com/123" })
@request.host = "live.gumroad.com"
allow_any_instance_of(@request.class).to receive(:fullpath).and_return("/123")
index
end
it "redirects to redirect_url" do
expect(response).to redirect_to("https://example.com/123")
end
end
context "when the host is not configured to redirect" do
it "renders successfully" do
index
expect(response).to be_successful
end
end
end
describe "#set_title" do
controller(ApplicationController) do
before_action :set_title
def index
head :ok
end
end
it "is Local Gumroad for development" do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("development"))
get :index
expect(assigns("title".to_sym)).to eq("Local Gumroad")
end
it "is Staging Gumroad for staging" do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("staging"))
get :index
expect(assigns("title".to_sym)).to eq("Staging Gumroad")
end
it "is Gumroad for production" do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
get :index
expect(assigns("title".to_sym)).to eq("Gumroad")
end
end
describe "default_url_options" do
it "adds protocol" do
expect(subject.default_url_options({})[:protocol]).to match(/^http/)
expect(subject.default_url_options[:protocol]).to match(/^http/)
end
end
describe "is_bot?" do
it "returns true for actual bots" do
request.env["HTTP_USER_AGENT"] = BOT_MAP.keys.sample
expect(subject.is_bot?).to be(true)
end
it "returns false for non bots" do
request.env["HTTP_USER_AGENT"] = "Mozilla-Like-Thing"
expect(subject.is_bot?).to be(false)
end
it "returns true for googlebotty stuff" do
request.env["HTTP_USER_AGENT"] = "something new googlebot"
expect(subject.is_bot?).to be(true)
end
end
describe "is_mobile?" do
it "returns true for mobile user agents" do
@request.user_agent = "Some Mobile Browser"
expect(subject.is_mobile?).to be(true)
end
it "returns false for desktop user agents" do
@request.user_agent = "Some Desktop Browser"
expect(subject.is_mobile?).to be(false)
end
end
describe "authenticate_user!" do
controller do
before_action :authenticate_user!
skip_before_action :verify_authenticity_token
def index
respond_to do |format|
format.json { render json: { success: true } }
format.js { render json: { success: true } }
format.html { head :ok }
end
end
end
context "with html request" do
describe "logged out" do
it "redirects logged-out users to login when trying to access admin w proper next" do
get :index
expect(response).to redirect_to "/login?next=%2Fanonymous"
end
end
end
%i[js json].each do |request_format|
context "with #{request_format} request" do
describe "no authentication" do
it "returns the correct json" do
get :index, format: request_format
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("Not found")
end
end
describe "with authentication" do
before do
sign_in create(:user)
end
it "returns the correct json" do
get :index, as: request_format
expect(response).to be_successful
# response.parsed_body cannot be used here as for JS format the content type is
# `text/javascript; charset=utf-8` and is parsed as String
expect(JSON.parse(response.body)["success"]).to be(true)
end
end
end
end
end
describe "after_sign_in_path_for" do
controller do
def index
redirect_to after_sign_in_path_for(logged_in_user)
end
end
describe "has email" do
before do
@user = create(:user)
sign_in @user
end
it "redirects the person home" do
get :index
expect(response).to redirect_to "/dashboard"
end
context "when next is present" do
it "redirects to next" do
get :index, params: { next: "/customers" }
expect(response).to redirect_to "/customers"
end
it "strips out extra slashes and redirects to next as path" do
get :index, params: { next: "////evil.org" }
expect(response).to redirect_to "/evil.org"
end
it "redirects to relative path if next is a subdomain URL" do
stub_const("ROOT_DOMAIN", "test.gumroad.com")
get :index, params: { next: "https://username.test.gumroad.com/l/sample" }
expect(response).to redirect_to "/l/sample"
end
end
end
end
describe "after_sign_out_path_for" do
before do
@product = create(:product, unique_permalink: "wq")
@user = create(:user, confirmed_at: 1.day.ago, username: "dude")
sign_in @user
end
describe "on product page" do
it "goes to appropriate page after logging out" do
allow(controller.request).to receive(:referrer).and_return("/l/wq")
expect(subject.send(:after_sign_out_path_for, @user)).to eq "/l/wq"
end
end
describe "on user page" do
it "goes to appropriate page after logging out" do
allow(controller.request).to receive(:referrer).and_return("/dude")
expect(subject.send(:after_sign_out_path_for, @user)).to eq "/dude"
end
end
describe "not on product page" do
it "goes to appropriate page after logging out" do
allow(controller.request).to receive(:referrer).and_return("/about")
expect(subject.send(:after_sign_out_path_for, @user)).to eq "/about"
end
end
end
describe "login_path_for" do
before do
@user = create(:user)
end
controller do
def index
@user = User.find(params[:id])
redirect_to login_path_for(@user)
end
end
describe "is_buyer" do
before do
@user = create(:user)
create(:purchase, purchaser: @user)
end
it "redirects to library" do
get :index, params: { id: @user.id }
expect(response).to redirect_to "/library"
end
end
describe "params[:next]" do
it "redirects to next" do
get :index, params: { id: @user.id, next: "/about" }
expect(response).to redirect_to "/about"
end
end
describe "has referrer" do
it "redirects to referrer" do
request.headers["HTTP_REFERER"] = "/about"
get :index, params: { id: @user.id }
expect(response).to redirect_to "/about"
end
context "when referrer is login path" do
it "doesn't redirect to referrer" do
request.headers["HTTP_REFERER"] = "/login"
get :index, params: { id: @user.id }
expect(response).to_not redirect_to "/login"
expect(response).to redirect_to "/dashboard"
end
end
end
end
describe "e404" do
it "raises the 404 routing error on missing template" do
expect do
get :jobs, format: "zip"
end.to raise_error(ActionController::UrlGenerationError)
end
it "raises the 404 routing error" do
expect do
subject.send(:e404)
end.to raise_error(ActionController::RoutingError)
end
end
describe "e404_page" do
it "raises the 404 routing error" do
expect do
subject.send(:e404_page)
end.to raise_error(ActionController::RoutingError)
end
end
describe "e404_json" do
controller do
def index
e404_json
end
end
it "returns the correct hash" do
get :index
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error"]).to eq("Not found")
end
end
describe "#strip_timestamp_location" do
it "strips the location name" do
# https://www.unicode.org/cldr/cldr-aux/charts/28/verify/zones/en.html
# The location name is useless for determining the timestamp for the purpose parsing it for
expected_timestamp = "Wed Jun 23 2021 14:32:31 GMT 0700"
expect(subject.send(:strip_timestamp_location, "Wed Jun 23 2021 14:32:31 GMT 0700")).to eq(expected_timestamp)
expect(subject.send(:strip_timestamp_location, "Wed Jun 23 2021 14:32:31 GMT 0700 (BST)")).to eq(expected_timestamp)
expect(subject.send(:strip_timestamp_location, "Wed Jun 23 2021 14:32:31 GMT 0700 (Pacific Daylight Time)")).to eq(expected_timestamp)
expect(subject.send(:strip_timestamp_location, "Wed Jun 23 2021 14:32:31 GMT 0700 (Novosibirsk Standard Time)")).to eq(expected_timestamp)
expect(subject.send(:strip_timestamp_location, "Wed Jun 23 2021 14:32:31 GMT 0700 (Moscow Standard Time (Volgograd))")).to eq(expected_timestamp)
end
it "returns nil when passing nil" do
expect(subject.send(:strip_timestamp_location, nil)).to eq(nil)
end
end
describe "#set_signup_referrer" do
before do
@request.env["HTTP_REFERER"] = "http://google.com"
end
it "uses referrer from request object" do
get :index
expect(session[:signup_referrer]).to eq("google.com")
end
it "uses referrer from _sref param" do
get :index, params: { _sref: "bing.com" }
expect(session[:signup_referrer]).to eq("bing.com")
end
it "preserves existing referrer" do
get :index
get :index, params: { _sref: "bing.com" }
expect(session[:signup_referrer]).to eq("google.com")
end
it "ignores referrer if user is logged in" do
user = create(:user)
sign_in user
get :index
expect(session).to_not have_key(:signup_referrer)
end
end
describe "#add_user_to_bugsnag" do
controller do
# We can't test `before_bugsnag_notify` in test mode, so we're using an action as a proxy
def index
# By default, Bugsnag reports the user's id as an IP address
$bugsnag_event = OpenStruct.new(user: { id: "127.0.0.1" })
add_user_to_bugsnag($bugsnag_event)
render plain: ""
end
end
it "does not add user details when not logged in" do
get :index
expect($bugsnag_event.user).to eq(id: "127.0.0.1")
end
it "adds user info when logged in" do
user = create(:user, username: "joe", name: "Joe", email: "joe@example.com")
expected_hash = {
email: "joe@example.com",
locale: user.locale,
id: user.id,
name: "Joe",
username: "joe",
}
allow(controller).to receive(:current_user).and_return(user)
get :index
expect($bugsnag_event.user).to include(expected_hash)
allow(controller).to receive(:current_user).and_return(nil)
allow(controller).to receive(:current_resource_owner).and_return(user)
get :index
expect($bugsnag_event.user).to include(expected_hash)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/robots_controller_spec.rb | spec/controllers/robots_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe RobotsController do
render_views
describe "GET index" do
before do
@sitemap_config = "Sitemap: https://example.com/sitemap.xml"
@user_agent_rules = ["User-agent: *", "Disallow: /purchases/"]
robots_service = instance_double(RobotsService)
allow(RobotsService).to receive(:new).and_return(robots_service)
allow(robots_service).to receive(:sitemap_configs).and_return([@sitemap_config])
allow(robots_service).to receive(:user_agent_rules).and_return(@user_agent_rules)
end
it "renders robots.txt" do
get :index, format: :txt
expect(response).to be_successful
expect(response.body).to include(@sitemap_config)
end
it "includes user agent rules" do
get :index, format: :txt
expect(response).to be_successful
@user_agent_rules.each do |rule|
expect(response.body).to include(rule)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/audience_controller_spec.rb | spec/controllers/audience_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe AudienceController, inertia: true do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { :audience }
end
it "renders Inertia component with zero followers" do
get :index
expect(response).to be_successful
expect_inertia.to render_component("Audience/Index")
expect(inertia.props[:total_follower_count]).to eq(0)
expect(inertia.props[:audience_data]).to be_nil
end
it "renders Inertia component with correct follower count and deferred audience data" do
create(:active_follower, user: seller)
get :index
expect(response).to be_successful
expect_inertia.to render_component("Audience/Index")
expect(inertia.props[:total_follower_count]).to eq(1)
expect(inertia.props[:audience_data]).to be_nil
end
context "when fetching the deferred audience data prop" do
before do
seller.update!(timezone: "UTC")
travel_to Time.utc(2021, 1, 3) do
create(:active_follower, user: seller).confirm!
follower = create(:active_follower, user: seller)
follower.confirm!
follower.mark_deleted!
end
request.headers["X-Inertia"] = "true"
request.headers["X-Inertia-Partial-Component"] = "Audience/Index"
request.headers["X-Inertia-Partial-Data"] = "audience_data"
end
it "returns audience_data with expected structure", :sidekiq_inline, :elasticsearch_wait_for_refresh do
get :index, params: { from: Time.utc(2021, 1, 1), to: Time.utc(2021, 1, 3) }
expect(response).to be_successful
expect(inertia.props.deep_symbolize_keys[:audience_data]).to eq(
dates: ["Friday, January 1st", "Saturday, January 2nd", "Sunday, January 3rd"],
start_date: "Jan 1, 2021",
end_date: "Jan 3, 2021",
by_date: {
new_followers: [0, 0, 2],
followers_removed: [0, 0, 1],
totals: [0, 0, 1]
},
first_follower_date: "Jan 3, 2021",
new_followers: 1
)
end
it "handles various timezone formats in date parameters" do
travel_to Time.utc(2024, 4, 15) do
create(:active_follower, user: seller).confirm!
end
mask = "%a %b %d %Y %H:%M:%S GMT-1200 (Changement de date)"
start_time = Time.utc(2024, 4, 1).strftime(mask)
end_time = Time.utc(2024, 4, 30).strftime(mask)
get :index, params: { from: start_time, to: end_time }
expect(response).to be_successful
expect(inertia.props.deep_symbolize_keys[:audience_data]).to include(
start_date: "Apr 1, 2024",
end_date: "Apr 30, 2024",
)
end
end
it "sets the last viewed dashboard cookie" do
get :index
expect(response.cookies["last_viewed_dashboard"]).to eq "audience"
end
end
describe "POST export" do
it_behaves_like "authorize called for action", :post, :export do
let(:record) { :audience }
end
let!(:follower) { create(:active_follower, user: seller) }
let(:options) { { "followers" => true, "customers" => false, "affiliates" => false } }
it "enqueues a job for sending the CSV" do
post :export, params: { options: options }, as: :json
expect(Exports::AudienceExportWorker).to have_enqueued_sidekiq_job(seller.id, seller.id, options)
expect(response).to have_http_status(:ok)
end
context "when admin is signed in and impersonates seller" do
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
controller.impersonate_user(seller)
end
it "queues sidekiq job for the admin" do
post :export, params: { options: options }, as: :json
expect(Exports::AudienceExportWorker).to have_enqueued_sidekiq_job(seller.id, admin_user.id, options)
expect(response).to have_http_status(:ok)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/comments_controller_spec.rb | spec/controllers/comments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe CommentsController do
include ManageSubscriptionHelpers
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:user) { create(:user) }
shared_examples_for "erroneous index request" do
it "responds with an error" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Not found"
end
end
shared_examples_for "erroneous create request" do
it "responds with an error without persisting any changes" do
expect do
post(:create, xhr: true, params:)
end.to_not change { product_post.present? ? product_post.comments.count : Comment.count }
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Not found"
end
end
shared_examples_for "erroneous destroy request" do
it "responds with an error" do
expect do
delete(:destroy, xhr: true, params:)
end.to_not change { comment }
expect(response).to have_http_status(:not_found)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Not found"
end
end
shared_examples_for "erroneous update request" do
it "responds with not found error" do
expect do
put(:update, xhr: true, params:)
end.to_not change { comment.reload }
expect(response).to have_http_status(http_status)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq error_message
end
end
shared_examples_for "not_found update request" do |http_status, error|
it_behaves_like "erroneous update request" do
let(:http_status) { :not_found }
let(:error_message) { "Not found" }
end
end
shared_examples_for "unauthorized update request" do |http_status, error|
it_behaves_like "erroneous update request" do
let(:http_status) { :unauthorized }
end
end
describe "GET index" do
let(:post) { create(:published_installment, link: product, installment_type: Installment::AUDIENCE_TYPE, shown_on_profile: true) }
let!(:comment1) { create(:comment, commentable: post, author: user, created_at: 1.minute.ago) }
let!(:comment2) { create(:comment, commentable: post) }
let!(:comment_on_another_post) { create(:comment) }
before do
stub_const("PaginatedCommentsPresenter::COMMENTS_PER_PAGE", 1)
end
context "when user is signed in" do
before do
sign_in user
end
context "when post exists" do
let(:params) { { post_id: post.external_id } }
# TODO: investigate how to make this work. CommentContext new object from controller doesn't match the object
# instantiated below, so the spec fails
# TODO :once figured out, add a spec for all other controller actions
# it_behaves_like "authorize called for action", :get, :index do
# let(:record) do
# CommentContext.new(
# comment: nil,
# commentable: post,
# purchase: nil
# )
# end
# let(:request_params) { params }
# end
it "returns paginated comments with pagination metadata" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:ok)
result = response.parsed_body
expect(result["comments"].length).to eq(1)
expect(result["comments"].first["id"]).to eq(comment1.external_id)
expect(result["pagination"]).to eq("count" => 2, "items" => 1, "pages" => 2, "page" => 1, "next" => 2, "prev" => nil, "last" => 2)
end
context "when 'page' query parameter is specified" do
let(:params) { { post_id: post.external_id, page: 2 } }
it "returns paginated comments for the specified page number with pagination metadata" do
get(:index, xhr: true, params:)
result = response.parsed_body
expect(result["comments"].length).to eq(1)
expect(result["comments"].first["id"]).to eq(comment2.external_id)
expect(result["pagination"]).to eq("count" => 2, "items" => 1, "pages" => 2, "page" => 2, "next" => nil, "prev" => 1, "last" => 2)
end
end
context "when the specified 'page' option is an overflowing page number" do
let(:params) { { post_id: post.external_id, page: 3 } }
it "raises an exception" do
expect do
get :index, xhr: true, params:
end.to raise_error(Pagy::OverflowError)
end
end
context "when post belongs to user's purchased product" do
let!(:purchase) { create(:purchase, link: product, purchaser: user, created_at: 1.second.ago) }
let(:post) { create(:published_installment, link: product, shown_on_profile: true) }
it "returns paginated comments with pagination metadata" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:ok)
result = response.parsed_body
expect(result["comments"].length).to eq(1)
expect(result["comments"].first["id"]).to eq(comment1.external_id)
expect(result["pagination"]).to eq("count" => 2, "items" => 1, "pages" => 2, "page" => 1, "next" => 2, "prev" => nil, "last" => 2)
end
end
context "when post is not published" do
let(:post) { create(:installment, link: product, installment_type: "product", published_at: nil) }
it_behaves_like "erroneous index request"
end
end
context "when post does not exist" do
let(:params) { { post_id: 1234 } }
it_behaves_like "erroneous index request"
end
end
context "when user is not signed in" do
let(:post) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) }
let(:params) { { post_id: post.external_id } }
it "responds with an error" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "You are not allowed to perform this action."
end
context "when the post is visible to everyone" do
let(:post) { create(:published_installment, link: product, installment_type: Installment::AUDIENCE_TYPE, shown_on_profile: true) }
let(:params) { { post_id: post.external_id } }
it "returns paginated comments with pagination metadata" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:ok)
result = response.parsed_body
expect(result["comments"].length).to eq(1)
expect(result["comments"].first["id"]).to eq(comment1.external_id)
expect(result["pagination"]).to eq("count" => 2, "items" => 1, "pages" => 2, "page" => 1, "next" => 2, "prev" => nil, "last" => 2)
end
end
context "when 'purchase_id' query parameter is specified that matches the id of the purchase of the post's product" do
let!(:purchase) { create(:purchase, link: product, created_at: 1.second.ago) }
let(:post) { create(:published_installment, link: product, shown_on_profile: true) }
let(:params) { { post_id: post.external_id, purchase_id: purchase.external_id } }
it "returns paginated comments with pagination metadata" do
get(:index, xhr: true, params:)
expect(response).to have_http_status(:ok)
result = response.parsed_body
expect(result["comments"].length).to eq(1)
expect(result["comments"].first["id"]).to eq(comment1.external_id)
expect(result["pagination"]).to eq("count" => 2, "items" => 1, "pages" => 2, "page" => 1, "next" => 2, "prev" => nil, "last" => 2)
end
end
end
end
describe "POST create" do
shared_examples_for "creates a comment" do
it "adds a comment to the post with the specified content" do
expect do
post(:create, xhr: true, params:)
end.to change { product_post.comments.count }.by(1)
comment = product_post.comments.first
expect(comment.content).to eq("Good article!")
expect(comment.commentable).to eq(product_post)
expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_USER_SUBMITTED)
expect(comment.author_id).to eq(author.id)
expect(comment.purchase).to be_nil
end
end
context "when user is signed in" do
before do
sign_in user
end
context "when post exists" do
let(:product_post) { create(:published_installment, link: product, installment_type: Installment::AUDIENCE_TYPE, shown_on_profile: true) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" } } }
include_examples "creates a comment" do
let(:author) { user }
end
context "when post belongs to user's purchased product" do
let!(:purchase) { create(:purchase, link: product, purchaser: user, created_at: 1.second.ago) }
let(:product_post) { create(:published_installment, link: product, shown_on_profile: true) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" } } }
it "adds a comment and persists the id of the purchase along with the comment" do
expect do
post(:create, xhr: true, params:)
end.to change { product_post.comments.count }.by(1)
comment = product_post.comments.first
expect(comment.content).to eq("Good article!")
expect(comment.parent_id).to be_nil
expect(comment.purchase).to eq(purchase)
end
context "when 'parent_id' is specified" do
let!(:parent_comment) { create(:comment, commentable: product_post) }
it "adds a reply comment with the id of the parent comment" do
expect do
post :create, xhr: true, params: { post_id: product_post.external_id, comment: { content: "Good article!", parent_id: parent_comment.external_id } }
end.to change { product_post.comments.count }.by(1)
expect(response).to have_http_status(:ok)
reply = product_post.comments.last
expect(reply.parent_id).to eq(parent_comment.id)
end
end
end
it "does not allow adding a comment with an adult keyword" do
expect do
post :create, xhr: true, params: { post_id: product_post.external_id, comment: { content: "nsfw comment" } }
end.to_not change { product_post.comments.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("Adult keywords are not allowed")
end
context "when post is not published" do
let(:product_post) { create(:installment, link: product, installment_type: "product", published_at: nil) }
it_behaves_like "erroneous create request"
end
end
context "when post does not exist" do
let(:params) { { post_id: 1234, comment: { content: "Good article!" } } }
let(:product_post) { nil }
it_behaves_like "erroneous create request"
end
end
context "when seller is signed in" do
let(:product_post) { create(:published_installment, link: product, installment_type: Installment::AUDIENCE_TYPE) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" } } }
before do
sign_in seller
end
include_examples "creates a comment" do
let(:author) { seller }
end
end
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
let(:product_post) { create(:published_installment, link: product, installment_type: Installment::AUDIENCE_TYPE) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" } } }
include_examples "creates a comment" do
let(:author) { user_with_role_for_seller }
end
end
context "when user is not signed in" do
let(:product_post) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" } } }
it "responds with an error" do
post(:create, xhr: true, params:)
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "You are not allowed to perform this action."
end
context "when 'purchase_id' query parameter is specified that matches the id of the purchase of the post's product" do
let(:purchase) { create(:purchase, link: product, full_name: "Jane Doe", created_at: 1.second.ago) }
let(:product_post) { create(:published_installment, link: product, shown_on_profile: true) }
let(:params) { { post_id: product_post.external_id, comment: { content: "Good article!" }, purchase_id: purchase.external_id } }
it "adds a comment and persists the id of the purchase along with the comment" do
expect do
post(:create, xhr: true, params:)
end.to change { product_post.comments.count }.by(1)
comment = product_post.comments.first
expect(comment.content).to eq("Good article!")
expect(comment.author_id).to be_nil
expect(comment.author_name).to eq("Jane Doe")
expect(comment.purchase).to eq(purchase)
end
end
end
end
describe "DELETE destroy" do
let(:post1) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) }
let(:post2) { create(:published_installment, link: create(:product), installment_type: "product", shown_on_profile: true) }
let(:post1_author) { seller }
let(:post2_author) { post2.seller }
let!(:post1_comment1) { create(:comment, commentable: post1, author: user) }
let!(:post1_comment2) { create(:comment, commentable: post1) }
let!(:post2_comment) { create(:comment, commentable: post2, author: user) }
context "when user is not signed in" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id } }
it "responds with an error" do
expect do
delete(:destroy, xhr: true, params:)
end.to_not change { comment.reload.alive? }.from(true)
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "You are not allowed to perform this action."
end
context "when 'purchase_id' query parameter is specified that matches the comment's associated purchase" do
let(:purchase) { create(:purchase, link: product, created_at: 1.second.ago) }
let(:product_post) { create(:published_installment, link: product, shown_on_profile: true) }
let!(:comment) { create(:comment, commentable: product_post, purchase:) }
let(:params) { { post_id: product_post.external_id, id: comment.external_id, purchase_id: purchase.external_id } }
it "deletes the comment" do
expect do
delete(:destroy, xhr: true, params:)
end.to change { comment.reload.alive? }.from(true).to(false)
.and change { product_post.comments.alive.count }.by(-1)
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
end
end
end
context "when commenter is signed in" do
before do
sign_in user
end
context "when commenter tries to delete own comment on the specified post" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id } }
it "soft deletes commenter's comment" do
expect do
delete(:destroy, xhr: true, params:)
end.to change { comment.reload.alive? }.from(true).to(false)
.and change { post1.comments.alive.count }.by(-1)
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
end
context "when a comment has replies" do
let!(:reply1) { create(:comment, commentable: post1, parent: comment, author: user) }
let!(:reply_to_reply1) { create(:comment, commentable: post1, parent: reply1) }
let!(:reply2) { create(:comment, commentable: post1, parent: comment) }
it "soft deletes the comment along with its replies" do
expect do
expect do
expect do
delete :destroy, xhr: true, params: { post_id: post1.external_id, id: reply1.external_id }
end.to change { reply1.reload.alive? }.from(true).to(false)
.and change { reply_to_reply1.reload.alive? }.from(true).to(false)
end.to_not change { comment.reload.alive? }
end.to_not change { reply2.reload.alive? }
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
end
end
end
context "when commenter tries to delete someone else's comment" do
let(:comment) { post1_comment2 }
let(:params) { { post_id: post1.external_id, id: comment.external_id } }
it "responds with an error" do
expect do
delete(:destroy, xhr: true, params:)
end.to_not change { comment.reload.alive? }.from(true)
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "You are not allowed to perform this action."
end
end
context "when commenter tries to delete own comment that does not belong to specified post" do
let(:comment) { post2_comment }
let(:params) { { post_id: post1.external_id, id: comment.external_id } }
it_behaves_like "erroneous destroy request"
end
end
shared_examples_for "destroy as seller or team member" do
context "when seller tries to delete a comment on own post" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id } }
it "soft deletes the comment" do
expect do
delete(:destroy, xhr: true, params:)
end.to change { comment.reload.alive? }.from(true).to(false)
.and change { post1.comments.alive.count }.by(-1)
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
end
end
context "when seller tries to delete a comment on someone else's post" do
let(:comment) { post2_comment }
let(:params) { { post_id: post2.external_id, id: comment.external_id } }
it "responds with an error" do
expect do
delete(:destroy, xhr: true, params:)
end.to_not change { comment.reload.alive? }.from(true)
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq error_message
end
end
end
context "when seller is signed in" do
before do
sign_in seller
end
include_examples "destroy as seller or team member" do
let(:error_message) { "You are not allowed to perform this action." }
end
end
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
include_examples "destroy as seller or team member" do
let(:error_message) { "Your current role as Admin cannot perform this action." }
end
end
end
describe "PUT update" do
let(:post1) { create(:published_installment, link: product, installment_type: "product", shown_on_profile: true) }
let(:post2) { create(:published_installment, link: create(:product), installment_type: "product", shown_on_profile: true) }
let(:post1_author) { seller }
let(:post2_author) { post2.seller }
let!(:post1_comment1) { create(:comment, commentable: post1, author: user) }
let!(:post1_comment2) { create(:comment, commentable: post1) }
let!(:post2_comment) { create(:comment, commentable: post2, author: user) }
context "when user is not signed in" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it "responds with an error" do
expect do
put(:update, xhr: true, params:)
end.to_not change { comment.reload }
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "You are not allowed to perform this action."
end
context "when 'purchase_id' query parameter is specified that matches the comment's associated purchase" do
let(:purchase) { create(:purchase, link: product, created_at: 1.second.ago) }
let(:product_post) { create(:published_installment, link: product, shown_on_profile: true) }
let!(:comment) { create(:comment, commentable: product_post, purchase:) }
let(:params) { { post_id: product_post.external_id, id: comment.external_id, purchase_id: purchase.external_id, comment: { content: "Nice article" } } }
it "updates the comment" do
expect do
put(:update, xhr: true, params:)
end.to change { comment.reload.content }.to("Nice article")
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
expect(response.parsed_body["comment"]["content"]["original"]).to eq("Nice article")
end
end
context "when post belongs to user's purchased recurring subscription whose plan changes", :vcr do
before(:each) do
setup_subscription
@product_post = create(:published_installment, link: @product)
@comment = create(:comment, commentable: @product_post, purchase: @original_purchase)
@subscription.update_current_plan!(new_variants: [@new_tier], new_price: @yearly_product_price)
@new_original_purchase = @subscription.reload.original_purchase
end
context "when 'purchase_id' query parameter matches the updated 'original_purchase'" do
it "updates the comment" do
expect do
put :update, xhr: true, params: { post_id: @product_post.external_id, id: @comment.external_id, purchase_id: @new_original_purchase.external_id, comment: { content: "Nice article" } }
end.to change { @comment.reload.content }.to("Nice article")
expect(response).to have_http_status(:ok)
expect(response.parsed_body["comment"]["content"]["original"]).to eq("Nice article")
end
end
context "when 'purchase_id' query parameter matches the archived 'original_purchase' and does not match the updated 'original_purchase'" do
it "updates the comment" do
expect do
put :update, xhr: true, params: { post_id: @product_post.external_id, id: @comment.external_id, purchase_id: @original_purchase.external_id, comment: { content: "Nice article" } }
end.to change { @comment.reload.content }.to("Nice article")
expect(response).to have_http_status(:ok)
expect(response.parsed_body["comment"]["content"]["original"]).to eq("Nice article")
end
end
end
end
context "when commenter is signed in" do
before do
sign_in user
end
context "when commenter tries to update own comment on the specified post" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice\t\t\t\tarticle!!!\n\n\n\n\tKeep it up. <script>evil</script>" } } }
it "updates commenter's comment" do
expect do
put(:update, xhr: true, params:)
end.to change { comment.reload.content }.to("Nice\t\t\t\tarticle!!!\n\n\tKeep it up. <script>evil</script>")
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
expect(response.parsed_body["comment"]["content"]["original"]).to eq("Nice\t\t\t\tarticle!!!\n\n\tKeep it up. <script>evil</script>")
expect(response.parsed_body["comment"]["content"]["formatted"]).to eq("Nice\t\t\t\tarticle!!!\n\n\tKeep it up. <script>evil</script>")
end
it "does not allow updating the comment with an adult keyword" do
expect do
put :update, xhr: true, params: { post_id: post1.external_id, id: comment.external_id, comment: { content: "nsfw comment" } }
end.to_not change { comment.reload.content }
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("Adult keywords are not allowed")
end
end
context "when commenter tries to update someone else's comment" do
let(:comment) { post1_comment2 }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it_behaves_like "unauthorized update request" do
let(:error_message) { "You are not allowed to perform this action." }
end
end
context "when commenter tries to update own comment that does not belong to specified post" do
let(:comment) { post2_comment }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it_behaves_like "not_found update request"
end
end
context "with seller signed in" do
before do
sign_in seller
end
context "when seller tries to update a user's comment on own post" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it_behaves_like "unauthorized update request" do
let(:error_message) { "You are not allowed to perform this action." }
end
end
context "when seller tries to update own comment on own post" do
let(:comment) { create(:comment, commentable: post1, author: seller) }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it "updates the comment" do
expect do
put(:update, xhr: true, params:)
end.to change { comment.reload.content }.to("Nice article")
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq true
expect(response.parsed_body["comment"]["content"]["original"]).to eq("Nice article")
end
end
end
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
context "when trying to update a user's comment on seller post" do
let(:comment) { post1_comment1 }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it_behaves_like "unauthorized update request" do
let(:error_message) { "Your current role as Admin cannot perform this action." }
end
end
context "when trying to update seller's comment on seller post" do
let(:comment) { create(:comment, commentable: post1, author: seller) }
let(:params) { { post_id: post1.external_id, id: comment.external_id, comment: { content: "Nice article" } } }
it_behaves_like "unauthorized update request" do
let(:error_message) { "Your current role as Admin cannot perform this action." }
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/controllers/home_controller_spec.rb | spec/controllers/home_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HomeController do
render_views
describe "GET small_bets" do
it "renders successfully" do
get :small_bets
expect(response).to be_successful
expect(assigns(:title)).to eq("Small Bets by Gumroad")
expect(assigns(:hide_layouts)).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/controllers/purchases_controller_spec.rb | spec/controllers/purchases_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/order_association_with_cart_post_checkout"
include CurrencyHelper
describe PurchasesController, :vcr do
include ManageSubscriptionHelpers
render_views
let(:price) { 600 }
let(:product) { create(:product, price_cents: price) }
let(:zero_plus_link) { create(:product, price_range: "0+") }
let(:two_plus_link) { create(:product, price_range: "2+") }
let(:params) do
{ permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
cc_zipcode_required: "false",
cc_zipcode: "12345",
quantity: 1 }.merge(StripePaymentMethodHelper.success.to_stripejs_params)
end
let(:stripejs_params) do
{ permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
quantity: 1 }.merge(StripePaymentMethodHelper.success.to_stripejs_params)
end
let(:stripejs_params_declined) do
{ permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
quantity: 1 }.merge(StripePaymentMethodHelper.decline.to_stripejs_params)
end
let(:stripejs_card_error_params) do
{ card_data_handling_mode: "stripejs.0",
stripe_error: {
type: "card_error",
code: "cvc_check_failed",
message: "G'day mate. Your CVC aint right."
},
permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
quantity: 1 }
end
let(:stripejs_other_error_params) do
{ card_data_handling_mode: "stripejs.0",
stripe_error: {
type: "api_error",
message: "That's a knife?"
},
permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
quantity: 1 }
end
let(:invalid_zipcode_params) do
{ permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
cc_zipcode_required: "true",
cc_zipcode: "12345",
quantity: 1 }.merge(StripePaymentMethodHelper.success_zip_check_fails.with_zip_code.to_stripejs_params)
end
let(:invalid_zipcode_params_no_zip_code) do
{ permalink: product.unique_permalink,
email: "sahil@gumroad.com",
perceived_price_cents: price,
cc_zipcode_required: "true",
quantity: 1 }.merge(StripePaymentMethodHelper.success_zip_check_fails.to_stripejs_params)
end
let(:zero_plus_params) do
{ permalink: zero_plus_product.unique_permalink,
email: "mike2@gumroad.com",
perceived_price_cents: 0,
price_range: "0",
cc_zipcode_required: "false",
cc_zipcode: "12345",
quantity: 1 }
end
let(:two_plus_params) do
{ permalink: two_plus_product.unique_permalink,
email: "mike3@gumroad.com",
perceived_price_cents: 200,
price_range: "200",
cc_zipcode_required: "false",
cc_zipcode: "12345",
quantity: 1 }.merge(StripePaymentMethodHelper.success.to_stripejs_params)
end
let(:sca_params) do
{ permalink: product.unique_permalink,
email: Faker::Internet.email,
perceived_price_cents: price,
quantity: 1 }.merge(StripePaymentMethodHelper.success_with_sca.to_stripejs_params)
end
# Created a second link that is different from the first one and lets us simulate 2 different purchases.
let(:other_link) { create(:product, price_cents: price) }
let(:other_params) do
{ permalink: other_product.unique_permalink,
email: "mike@gumroad.com",
perceived_price_cents: price,
cc_zipcode_required: "false",
cc_zipcode: "12345",
quantity: 1 }.merge(StripePaymentMethodHelper.success.to_stripejs_params)
end
let(:seller) { create(:named_seller) }
before do
cookies[:_gumroad_guid] = SecureRandom.uuid
end
context "within seller area" do
include_context "with user signed in as admin for seller"
describe "PUT update" do
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller:, email: "k@gumroad.com") }
let(:obfuscated_id) { ObfuscateIds.encrypt(purchase.id) }
it_behaves_like "authorize called for action", :put, :update do
let(:record) { purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { id: obfuscated_id, email: " test@gumroad.com" } }
end
it "allows to update email address" do
put :update, params: { id: obfuscated_id, email: " test@gumroad.com" }
expect(response.parsed_body["success"]).to be(true)
expect(purchase.reload.email).to eq "test@gumroad.com"
end
it "updates email addresses of bundle product purchases" do
bundle_purchase = create(:purchase, link: create(:product, :bundle, user: seller))
bundle_purchase.create_artifacts_and_send_receipt!
put :update, params: { id: bundle_purchase.external_id, email: "newemail@gumroad.com" }
expect(response.parsed_body["success"]).to be(true)
expect(bundle_purchase.reload.email).to eq("newemail@gumroad.com")
expect(bundle_purchase.product_purchases.map(&:email)).to all(eq("newemail@gumroad.com"))
end
it "allows to update giftee_email address" do
product = create(:product, user: seller)
gifter_email = "gifter@foo.com"
giftee_email = "giftee@foo.com"
gift = create(:gift, gifter_email:, giftee_email:, link: product)
gifter_purchase = create(:purchase, link: product,
seller:,
price_cents: product.price_cents,
email: gifter_email,
purchase_state: "successful",
is_gift_sender_purchase: true,
stripe_transaction_id: "ch_zitkxbhds3zqlt",
can_contact: true)
gift.gifter_purchase = gifter_purchase
gift.giftee_purchase = create(:purchase, link: product,
seller:,
email: giftee_email,
price_cents: 0,
is_gift_receiver_purchase: true,
purchase_state: "gift_receiver_purchase_successful",
can_contact: true)
gift.mark_successful
gift.save!
put :update, params: { id: ObfuscateIds.encrypt(gifter_purchase.id), giftee_email: "new_giftee@example.com" }
expect(response.parsed_body["success"]).to be(true)
expect(gift.reload.giftee_email).to eq "new_giftee@example.com"
expect(gift.giftee_purchase.email).to eq("new_giftee@example.com")
end
it "allows to update shipping information for the seller" do
put :update, params: { id: obfuscated_id, street_address: "1640 3rd Street", city: "San Francisco", state: "CA", zip_code: "94107", country: "United States" }
expect(response.parsed_body["success"]).to be(true)
purchase.reload
expect(purchase.street_address).to eq "1640 3rd Street"
expect(purchase.city).to eq "San Francisco"
expect(purchase.state).to eq "CA"
expect(purchase.zip_code).to eq "94107"
expect(purchase.country).to eq "United States"
end
it "does not change shipping information for blank params" do
purchase.update!(street_address: "1640 3rd Street", city: "San Francisco", state: "CA", zip_code: "94107", country: "United States")
put :update, params: { id: obfuscated_id, full_name: "John Doe", street_address: "", city: "", state: "", zip_code: "", country: "" }
expect(response.parsed_body["success"]).to be(true)
purchase.reload
expect(purchase.full_name).to eq "John Doe"
expect(purchase.street_address).to eq "1640 3rd Street"
expect(purchase.city).to eq "San Francisco"
expect(purchase.state).to eq "CA"
expect(purchase.zip_code).to eq "94107"
expect(purchase.country).to eq "United States"
end
it "does not allow to update if signed in user is not a seller" do
sign_in create(:user)
put :update, params: { id: obfuscated_id, street_address: "1640 3rd Street", city: "San Francisco", state: "CA", zip_code: "94107", country: "United States" }
expect(response.parsed_body["success"]).to be(false)
end
end
describe "multiseat license" do
before do
@product = create(:membership_product, is_multiseat_license: true, user: seller)
end
it "derives product's `is_multiseat_license` for new purchases" do
purchase = create(:purchase, link: @product)
expect(purchase.is_multiseat_license).to eq(true)
@product.update(is_multiseat_license: false)
new_purchase = create(:purchase, link: @product.reload)
expect(purchase.reload.is_multiseat_license).to eq(true)
expect(new_purchase.is_multiseat_license).to eq(false)
end
it "updates quantity for purchase with multiseat license enabled" do
purchase = create(:purchase, link: @product)
expect(purchase.quantity).to eq(1)
put :update, params: { id: purchase.external_id, quantity: 2 }
expect(response.parsed_body["success"]).to be(true)
expect(purchase.reload.quantity).to eq(2)
end
it "does not update quantity for purchase with multiseat license disabled" do
@product.update(is_multiseat_license: false)
purchase = create(:purchase, link: @product)
expect(purchase.is_multiseat_license).to eq(false)
expect(purchase.quantity).to eq(1)
put :update, params: { id: purchase.external_id, quantity: 2 }
expect(purchase.reload.quantity).to eq(1)
end
end
describe "refund" do
let(:seller) { create(:user, unpaid_balance_cents: 200) }
it_behaves_like "authorize called for action", :put, :refund do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { id: @obfuscated_id, format: :json } }
end
before do
@l = create(:product, user: seller)
@p = create(:purchase_in_progress, link: @l, seller: @l.user, price_cents: 100, total_transaction_cents: 100, fee_cents: 30,
chargeable: create(:chargeable))
@p.process!
@p.mark_successful!
@obfuscated_id = ObfuscateIds.encrypt(@p.id)
@old_paypal_purchase = create(:purchase_in_progress, link: @l, seller: @l.user, price_cents: 100, total_transaction_cents: 100, fee_cents: 30, created_at: 7.months.ago, card_type: "paypal")
@old_paypal_purchase.process!
@old_paypal_purchase.mark_successful!
end
it "404s for already refunded purchases" do
@p.update!(stripe_refunded: true)
put :refund, params: { id: @obfuscated_id, format: :json }
expect(response.parsed_body).to eq "success" => false, "error" => "Not found"
expect(response).to have_http_status(:not_found)
end
it "returns 404 for PayPal purchases that are more than 6 months old" do
put :refund, params: { id: @old_paypal_purchase.external_id, format: :json }
expect(response.parsed_body).to eq "success" => false, "error" => "Not found"
expect(response).to have_http_status(:not_found)
end
it "404s for non existent purchases" do
put :refund, params: { id: 121_212_121, format: :json }
expect(response.parsed_body).to eq "success" => false, "error" => "Not found"
expect(response).to have_http_status(:not_found)
end
it "404s for free 0+ purchases" do
l = create(:product, price_range: "0+", price_cents: 0, user: seller)
p = create(:purchase, link: l, seller: l.user, price_cents: 0, total_transaction_cents: 0,
stripe_fingerprint: nil, stripe_transaction_id: nil)
put :refund, params: { id: ObfuscateIds.encrypt(p.id), format: :json }
expect(response.parsed_body).to eq "success" => false, "error" => "Not found"
expect(response).to have_http_status(:not_found)
end
it "404s for purchases not belong to this user" do
other_user = create(:user, unpaid_balance_cents: 200)
oldproduct = @p.link
@p.link = create(:product, user: other_user)
@p.seller = @p.link.user
@p.save!
put :refund, params: { id: @obfuscated_id, format: :json }
expect(response.parsed_body).to eq "success" => false, "error" => "Not found"
expect(response).to have_http_status(:not_found)
@p.link = oldproduct
@p.save
end
it "sends refund email" do
expect do
put :refund, params: { id: @obfuscated_id, format: :json }
end.to have_enqueued_mail(CustomerMailer, :refund)
end
it "returns status message on success" do
put :refund, params: { id: @obfuscated_id, format: :json }
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body["message"]).to_not be(nil)
end
it "returns error message on failure" do
allow_any_instance_of(Purchase).to receive(:refund_and_save!).and_return(false)
put :refund, params: { id: @obfuscated_id, format: :json }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to_not be(nil)
end
it "displays insufficient funds error if creator's paypal account does not funds to refund the purchase" do
allow_any_instance_of(User).to receive(:native_paypal_payment_enabled?).and_return(true)
purchase = create(:purchase, link: @l, charge_processor_id: PaypalChargeProcessor.charge_processor_id,
merchant_account: create(:merchant_account_paypal, charge_processor_merchant_id: "EF7UQSZMFR3UU"),
paypal_order_id: "36842509RK4544740", stripe_transaction_id: "8LE286804S000725B")
put :refund, params: { id: purchase.external_id, format: :json }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to eq("Your PayPal account does not have sufficient funds to make this refund.")
end
it "displays an error when refund amount contains commas" do
put :refund, params: { id: @obfuscated_id, amount: "1,00", format: :json }
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Commas not supported in refund amount.")
end
it "issues a full refund when total amount is passed as param" do
put :refund, params: { id: @obfuscated_id, amount: "1.00", format: :json }
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["id"]).to eq(@p.external_id)
expect(response.parsed_body["partially_refunded"]).to eq(false)
end
it "issues a partial refund when partial amount is passed as param" do
put :refund, params: { id: @obfuscated_id, amount: "0.50", format: :json }
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["id"]).to eq(@p.external_id)
expect(response.parsed_body["partially_refunded"]).to eq(true)
end
context "when product is sold in a single unit currency type" do
before do
@l.update!(price_currency_type: "jpy", price_cents: 1000)
@p1 = create(:purchase_in_progress,
link: @l,
seller: @l.user,
price_cents: 914,
total_transaction_cents: 100,
fee_cents: 54,
displayed_price_cents: 1000,
displayed_price_currency_type: "jpy",
rate_converted_to_usd: "109.383",
chargeable: create(:chargeable))
@p1.process!
@p1.mark_successful!
@obfuscated_id = ObfuscateIds.encrypt(@p1.id)
allow_any_instance_of(User).to receive(:unpaid_balance_cents).and_return(100_00)
end
it "issues a partial refund when partial amount is passed as param" do
put :refund, params: { id: @obfuscated_id, amount: "500", format: :json }
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["id"]).to eq(@p1.external_id)
expect(response.parsed_body["partially_refunded"]).to eq(true)
end
it "issues a full refund when amount param is missing" do
put :refund, params: { id: @obfuscated_id, format: :json }
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["id"]).to eq(@p1.external_id)
expect(response.parsed_body["partially_refunded"]).to eq(false)
end
it "issues a full refund when total amount is passed as param" do
put :refund, params: { id: @obfuscated_id, amount: "1000", format: :json }
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["id"]).to eq(@p1.external_id)
expect(response.parsed_body["partially_refunded"]).to eq(false)
end
end
context "when there's a record invalid exception" do
before do
allow_any_instance_of(Purchase).to receive(:refund!).and_raise(ActiveRecord::RecordInvalid)
end
it "notifies Bugsnag and responds with error message" do
expect(Bugsnag).to receive(:notify).with(instance_of(ActiveRecord::RecordInvalid))
put :refund, params: { id: @obfuscated_id, amount: "1000", format: :json }
expect(response.parsed_body).to eq "success" => false, "message" => "Sorry, something went wrong."
expect(response).to have_http_status(:unprocessable_content)
end
end
end
describe "#search" do
it_behaves_like "authorize called for action", :get, :search do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
end
it "returns some proper json" do
product = create(:product, user: seller)
create(:purchase, email: "bob@exampleabc.com", link: product, seller: product.user, created_at: 6.days.ago)
create(:purchase, email: "jane@exampleefg.com", link: product, seller: product.user)
create(:purchase, link: product, seller: product.user, full_name: "edgar abc gumstein")
index_model_records(Purchase)
get :search, params: { query: "bob" }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["email"]).to eq "bob@exampleabc.com"
end
it "returns results sorted by score" do
product = create(:product, user: seller)
purchases = [
create(:purchase, email: "a@a.com", link: product, full_name: "John John"),
create(:purchase, email: "a@a.com", link: product, full_name: "John John John"),
create(:purchase, email: "a@a.com", link: product, full_name: "John")
]
index_model_records(Purchase)
get :search, params: { query: "john" }
expect(response.parsed_body[0]["id"]).to eq purchases[1].external_id
expect(response.parsed_body[1]["id"]).to eq purchases[0].external_id
expect(response.parsed_body[2]["id"]).to eq purchases[2].external_id
end
it "supports pagination" do
product = create(:product, user: seller)
purchases = [
create(:purchase, email: "bob@exampleabc.com", link: product, seller:, created_at: 6.days.ago),
create(:purchase, email: "bob@exampleabc.com", link: product, seller:, created_at: 5.days.ago)
]
stub_const("#{described_class}::SEARCH_RESULTS_PER_PAGE", 1)
index_model_records(Purchase)
get :search, params: { query: "bob" }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["id"]).to eq purchases[1].external_id
get :search, params: { query: "bob", page: 2 }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["id"]).to eq purchases[0].external_id
end
it "does not return the recurring purchase" do
product = create(:membership_product, user: seller, subscription_duration: :monthly)
user = create(:user, email: "subuser@example.com", credit_card: create(:credit_card))
subscription = create(:subscription, link: product, user:, created_at: 3.days.ago)
create(:purchase, email: user.email, is_original_subscription_purchase: true, link: product, subscription:, purchaser: user)
create(:purchase, email: user.email, is_original_subscription_purchase: false, link: product, subscription:, purchaser: user)
index_model_records(Purchase)
get :search, params: { query: "sub" }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["email"]).to eq "subuser@example.com"
expect(response.parsed_body[0]["subscription_id"]).to eq subscription.external_id
end
it "does not return both gift purchases" do
product = create(:product, user: seller)
create(:purchase, link: product, seller:, purchase_state: "successful")
gifter_email = "gifter@foo.com"
giftee_email = "giftee@domain.org"
gift = create(:gift, gifter_email:, giftee_email:, link: product)
gifter_purchase = create(:purchase, link: product,
seller:,
price_cents: product.price_cents,
email: gifter_email,
purchase_state: "successful",
is_gift_sender_purchase: true,
stripe_transaction_id: "ch_zitkxbhds3zqlt",
can_contact: true)
gift.gifter_purchase = gifter_purchase
gift.giftee_purchase = create(:purchase, link: product,
seller:,
email: giftee_email,
price_cents: 0,
is_gift_receiver_purchase: true,
purchase_state: "gift_receiver_purchase_successful",
can_contact: true)
gift.mark_successful
gift.save!
index_model_records(Purchase)
get :search, params: { query: giftee_email }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["email"]).to eq giftee_email
end
it "includes variant details" do
product = create(:product, user: seller)
category = create(:variant_category, link: product, title: "Color")
variant = create(:variant, variant_category: category, name: "Blue")
create(:purchase, email: "bob@exampleabc.com", link: product, seller: product.user, created_at: 6.days.ago, variant_attributes: [variant])
create(:purchase, email: "jane@exampleefg.com", link: product, seller: product.user)
index_model_records(Purchase)
get :search, params: { query: "bob" }
expect(response.parsed_body[0]["variants"]).to eq ({
category.external_id => {
"title" => category.title,
"selected_variant" => {
"id" => variant.external_id,
"name" => variant.name
}
}
})
end
context "for subscriptions that have been upgraded" do
before do
setup_subscription
end
it "includes the upgraded purchase" do
seller = @product.user
@original_purchase.update!(full_name: "Sally Gumroad")
travel_to(@originally_subscribed_at + 1.month) do
params = {
price_id: @yearly_product_price.external_id,
variants: [@original_tier.external_id],
use_existing_card: true,
perceived_price_cents: @original_tier_yearly_price.price_cents,
perceived_upgrade_price_cents: @original_tier_yearly_upgrade_cost_after_one_month,
}
result =
Subscription::UpdaterService.new(subscription: @subscription,
gumroad_guid: "abc123",
params:,
logged_in_user: @user,
remote_ip: "1.1.1.1").perform
expect(result[:success]).to eq true
index_model_records(Purchase)
sign_in seller
get :search, params: { query: "sally" }
expect(response.parsed_body.length).to eq 1
expect(response.parsed_body[0]["purchase_email"]).to eq @original_purchase.email
end
end
end
end
describe "change_can_contact" do
before do
@product = create(:product, user: seller)
@purchase = create(:purchase, link: @product)
end
it_behaves_like "authorize called for action", :post, :change_can_contact do
let(:record) { @purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { id: ObfuscateIds.encrypt(@purchase.id) } }
end
it "changes can_contact and returns HTTP success" do
expect do
post :change_can_contact, params: { id: @purchase.external_id, can_contact: false }
end.to change { @purchase.reload.can_contact }.from(true).to(false)
expect(response).to be_successful
expect do
post :change_can_contact, params: { id: @purchase.external_id, can_contact: true }
end.to change { @purchase.reload.can_contact }.from(false).to(true)
expect(response).to be_successful
expect do
post :change_can_contact, params: { id: @purchase.external_id, can_contact: true }
end.to_not change { @purchase.reload.can_contact }
expect(response).to be_successful
end
end
describe "POST cancel_preorder_by_seller" do
let(:purchase) { create(:preorder_authorization_purchase, price_cents: 300) }
let(:seller) { purchase.seller }
it_behaves_like "authorize called for action", :post, :cancel_preorder_by_seller do
let(:record) { purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { id: ObfuscateIds.encrypt(purchase.id) } }
end
it "returns 404 json for invalid purchase" do
expect do
post :cancel_preorder_by_seller, params: { id: ObfuscateIds.encrypt(999_999) }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
context "with successful preorder" do
let(:preorder_link) { create(:preorder_link, link: purchase.link) }
before do
preorder = create(:preorder, preorder_link:, seller:, state: "authorization_successful")
purchase.update!(preorder:)
end
it "cancels the preorder" do
post :cancel_preorder_by_seller, params: { id: ObfuscateIds.encrypt(purchase.id) }
expect(response.parsed_body["success"]).to be(true)
expect(purchase.preorder.reload.state).to eq("cancelled")
end
end
end
describe "GET export" do
let(:params) { {} }
before do
@product = create(:product, user: seller, custom_fields: [create(:custom_field, name: "Height"), create(:custom_field, name: "Age")])
@purchase_1 = create(:purchase, link: @product, purchase_custom_fields: [build(:purchase_custom_field, name: "Age", value: "25")])
@purchase_2 = create(:purchase, link: @product, purchase_custom_fields: [build(:purchase_custom_field, name: "Citizenship", value: "Japan")])
@purchase_3 = create(:purchase, link: build(:product, user: seller))
create(:purchase)
index_model_records(Purchase)
end
def expect_correct_csv(csv_string)
csv = CSV.parse(csv_string)
expect(csv.size).to eq(5)
expect(csv[0]).to eq(Exports::PurchaseExportService::PURCHASE_FIELDS + ["Age", "Height", "Citizenship"])
# Test the correct purchase is listed with the expected custom fields values.
expect([csv[1].first] + csv[1].last(3)).to eq([@purchase_1.external_id, "25", nil, nil])
expect([csv[2].first] + csv[2].last(3)).to eq([@purchase_2.external_id, nil, nil, "Japan"])
expect([csv[3].first] + csv[3].last(3)).to eq([@purchase_3.external_id, nil, nil, nil])
expect([csv[4].first] + csv[4].last(3)).to eq(["Totals", nil, nil, nil])
end
it_behaves_like "authorize called for action", :get, :export do
let(:record) { Purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :index? }
end
context "when number of sales is larger than threshold" do
before do
stub_const("Exports::PurchaseExportService::SYNCHRONOUS_EXPORT_THRESHOLD", 1)
end
it "queues sidekiq job and redirects to customers path with flash message" do
get :export
export = SalesExport.last!
expect(export.recipient).to eq(user_with_role_for_seller)
expect(Exports::Sales::CreateAndEnqueueChunksWorker).to have_enqueued_sidekiq_job(export.id)
expect(flash[:notice]).to eq("You will receive an email in your inbox with the data you've requested shortly.")
expect(response).to redirect_to(customers_path)
expect(response).to have_http_status(:see_other)
end
context "when running sidekiq jobs" do
it "results with the expected compiled CSV being emailed", :sidekiq_inline do
stub_const("Exports::Sales::CreateAndEnqueueChunksWorker::MAX_PURCHASES_PER_CHUNK", 2)
get :export
email = ActionMailer::Base.deliveries.last
expect(email.to).to eq([user_with_role_for_seller.email])
expect_correct_csv(email.body.parts.last.body.to_s)
end
end
context "when admin is signed in and impersonates seller" do
before do
@admin_user = create(:admin_user)
sign_in @admin_user
controller.impersonate_user(seller)
end
it "queues sidekiq job for the admin" do
get :export
export = SalesExport.last!
expect(export.recipient).to eq(@admin_user)
expect(Exports::Sales::CreateAndEnqueueChunksWorker).to have_enqueued_sidekiq_job(export.id)
expect(flash[:notice]).to eq("You will receive an email in your inbox with the data you've requested shortly.")
expect(response).to redirect_to(customers_path)
expect(response).to have_http_status(:see_other)
end
end
end
context "when sales data is smaller than threshold" do
it "sends data as CSV" do
get :export
expect(response.header["Content-Type"]).to include "text/csv"
expect_correct_csv(response.body.to_s)
end
it "sends data as CSV with purchases in the correct order", :elasticsearch_wait_for_refresh do
# We don't expect ES to return documents in any specific order,
# because we expect the purchases.find_each in #purchases_data to order them.
# The following lines manufactures a situation where ES will return purchase_2 after purchase_3:
@purchase_2.__elasticsearch__.delete_document
@purchase_2.__elasticsearch__.index_document
get :export
expect(response.header["Content-Type"]).to include "text/csv"
expect_correct_csv(response.body.to_s)
end
end
it "can filter by products and variants" do
category = create(:variant_category, link: create(:product, user: seller))
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/links_controller_spec.rb | spec/controllers/links_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/affiliate_cookie_concern"
require "shared_examples/authorize_called"
require "shared_examples/collaborator_access"
require "shared_examples/with_sorting_and_pagination"
require "inertia_rails/rspec"
def e404_test(action)
it "404s when link isn't found" do
expect { get action, params: { id: "NOT real" } }.to raise_error(ActionController::RoutingError)
end
end
describe LinksController, :vcr, inertia: true do
render_views
context "within seller area" do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
describe "GET index" do
before do
@membership1 = create(:subscription_product, user: seller)
@membership2 = create(:subscription_product, user: seller)
@unpublished_membership = create(:subscription_product, user: seller, purchase_disabled_at: Time.current)
@other_membership = create(:subscription_product)
@product1 = create(:product, user: seller)
@product2 = create(:product, user: seller)
@unpublished_product = create(:product, user: seller, purchase_disabled_at: Time.current)
@other_product = create(:product)
end
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Link }
end
it "returns seller's products" do
get :index
memberships = assigns(:memberships)
expect(memberships).to include(@membership1)
expect(memberships).to include(@membership2)
expect(memberships).to include(@unpublished_membership)
expect(memberships).to_not include(@other_membership)
products = assigns(:products)
expect(products).to include(@product1)
expect(products).to include(@product2)
expect(products).to include(@unpublished_product)
expect(products).to_not include(@other_product)
end
it "does not return the deleted products" do
@membership2.update!(deleted_at: Time.current)
@product2.update!(deleted_at: Time.current)
get :index
expect(assigns(:memberships)).to_not include(@membership2)
expect(assigns(:products)).to_not include(@product2)
end
it "does not return archived products" do
@membership2.update!(archived: true)
@product2.update!(archived: true)
get :index
expect(assigns(:memberships)).to_not include(@membership2)
expect(assigns(:products)).to_not include(@product2)
end
describe "shows the correct number of sales" do
def expect_sales_count_in_inertia_response(expected_count)
products = inertia.props[:react_products_page_props][:products]
expect(products).to be_present, "Expected products in Inertia.js response"
expect(products.first[:successful_sales_count]).to eq(expected_count)
end
it "with a single sale" do
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(1)
get(:index)
expect(response).to be_successful
expect(inertia).to render_component("Products/Index")
expect_sales_count_in_inertia_response(1)
end
it "with over a thousand sales, comma-delimited" do
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(3_030)
get(:index)
expect(response).to be_successful
expect(inertia).to render_component("Products/Index")
expect_sales_count_in_inertia_response(3_030)
end
it "shows comma-delimited pre-orders count" do
@product1.update_attribute(:is_in_preorder_state, true)
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(424_242)
get(:index)
expect(response).to be_successful
expect(inertia).to render_component("Products/Index")
expect_sales_count_in_inertia_response(424_242)
end
it "shows comma-delimited subscribers count" do
create(:subscription_product, user: seller)
allow_any_instance_of(Link).to receive(:successful_sales_count).and_return(1_111)
get(:index)
expect(response).to be_successful
expect(inertia).to render_component("Products/Index")
expect_sales_count_in_inertia_response(1_111)
end
end
describe "visible product URLs" do
it "shows product URL without the protocol part" do
get :index
expect(response).to be_successful
expect(inertia).to render_component("Products/Index")
products = inertia.props[:react_products_page_props][:products]
expect(products).to be_present
expect(products.first[:url_without_protocol]).to be_present
end
end
end
describe "GET memberships_paged" do
before do
@memberships_per_page = 2
stub_const("LinksController::PER_PAGE", @memberships_per_page)
end
it_behaves_like "authorize called for action", :get, :memberships_paged do
let(:record) { Link }
let(:policy_method) { :index? }
end
describe "membership sorting + pagination", :elasticsearch_wait_for_refresh do
include_context "with products and memberships"
it_behaves_like "an API for sorting and pagination", :memberships_paged do
let!(:default_order) { [membership2, membership3, membership4, membership1] }
let!(:columns) do
{
"name" => [membership1, membership2, membership3, membership4],
"successful_sales_count" => [membership4, membership1, membership3, membership2],
"revenue" => [membership4, membership1, membership3, membership2],
"display_price_cents" => [membership4, membership3, membership2, membership1]
}
end
let!(:boolean_columns) { { "status" => [membership3, membership4, membership2, membership1] } }
end
end
describe "more than 2n visible memberships" do
before do
@memberships_count = 2 * @memberships_per_page + 1
@memberships_count.times { create(:subscription_product, user: seller) }
end
it "returns success on page 1" do
get :memberships_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @memberships_per_page
end
it "returns success on page 2" do
get :memberships_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq @memberships_per_page
end
it "returns success on page 3" do
get :memberships_paged, params: { page: 3 }
expect(response.parsed_body["entries"].length).to eq 1
end
end
describe "between n and 2n visible memberships" do
before do
@memberships_count = @memberships_per_page + 1
@memberships_count.times { create(:subscription_product, user: seller) }
end
it "returns correctly on page 1" do
get :memberships_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @memberships_per_page
end
it "returns correctly on page 2" do
get :memberships_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq 1
end
it "raises on page overflow" do
expect { get :memberships_paged, params: { page: 3 } }.to raise_error(Pagy::OverflowError)
end
describe "has some deleted memberships" do
before do
3.times { create(:subscription_product, user: seller, deleted_at: Time.current) }
end
it "returns correctly on page 1" do
get :memberships_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @memberships_per_page
end
it "returns correctly on page 2" do
get :memberships_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq 1
end
it "raises on page overflow" do
expect { get :memberships_paged, params: { page: 3 } }.to raise_error(Pagy::OverflowError)
end
end
end
describe "< n visible memberships" do
before do
@published_count = @memberships_per_page - 1
@published_count.times { create(:subscription_product, user: seller) }
end
it "returns correctly on page 1" do
get :memberships_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @memberships_per_page - 1
end
it "raises on page overflow" do
expect { get :memberships_paged, params: { page: 2 } }.to raise_error(Pagy::OverflowError)
end
end
end
describe "GET products_paged" do
before do
@products_per_page = 2
stub_const("LinksController::PER_PAGE", @products_per_page)
end
it_behaves_like "authorize called for action", :get, :products_paged do
let(:record) { Link }
let(:policy_method) { :index? }
end
describe "non-membership sorting + pagination", :elasticsearch_wait_for_refresh do
include_context "with products and memberships"
it_behaves_like "an API for sorting and pagination", :products_paged do
let!(:default_order) { [product1, product3, product4, product2] }
let!(:columns) do
{
"name" => [product1, product2, product3, product4],
"successful_sales_count" => [product1, product2, product3, product4],
"revenue" => [product3, product2, product1, product4],
"display_price_cents" => [product3, product4, product2, product1]
}
end
let!(:boolean_columns) { { "status" => [product3, product4, product1, product2] } }
end
end
describe "more than 2n visible products" do
before do
@products_count = 2 * @products_per_page + 1
@products_count.times { create(:product, user: seller) }
end
it "returns success on page 1" do
get :products_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @products_per_page
end
it "returns success on page 2" do
get :products_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq @products_per_page
end
it "returns success on page 3" do
get :products_paged, params: { page: 3 }
expect(response.parsed_body["entries"].length).to eq 1
end
end
describe "between n and 2n visible products" do
before do
@products_count = @products_per_page + 1
@products_count.times { create(:product, user: seller) }
end
it "returns correctly on page 1" do
get :products_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @products_per_page
end
it "returns correctly on page 2" do
get :products_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq 1
end
it "raises on page overflow" do
expect { get :products_paged, params: { page: 3 } }.to raise_error(Pagy::OverflowError)
end
describe "has some deleted products" do
before do
3.times { create(:product, user: seller, deleted_at: Time.current) }
end
it "returns correctly on page 1" do
get :products_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @products_per_page
end
it "returns correctly on page 2" do
get :products_paged, params: { page: 2 }
expect(response.parsed_body["entries"].length).to eq 1
end
it "raises on page overflow" do
expect { get :products_paged, params: { page: 3 } }.to raise_error(Pagy::OverflowError)
end
end
end
describe "< n visible products" do
before do
@published_count = @products_per_page - 1
@published_count.times { create(:product, user: seller) }
end
it "returns correctly on page 1" do
get :products_paged, params: { page: 1 }
expect(response.parsed_body["entries"].length).to eq @products_per_page - 1
end
it "raises on page overflow" do
expect { get :products_paged, params: { page: 2 } }.to raise_error(Pagy::OverflowError)
end
end
end
%w[edit unpublish publish destroy].each do |action|
describe "##{action}" do
e404_test(action.to_sym)
end
end
describe "POST publish" do
before do
@disabled_link = create(:physical_product, purchase_disabled_at: Time.current, user: seller)
end
it_behaves_like "authorize called for action", :post, :publish do
let(:record) { @disabled_link }
let(:request_params) { { id: @disabled_link.unique_permalink } }
end
it_behaves_like "collaborator can access", :post, :publish do
let(:product) { @disabled_link }
let(:request_params) { { id: @disabled_link.unique_permalink } }
let(:response_attributes) { { "success" => true } }
end
it "enables a disabled link" do
post :publish, params: { id: @disabled_link.unique_permalink }
expect(response.parsed_body["success"]).to eq(true)
expect(@disabled_link.reload.purchase_disabled_at).to be_nil
end
context "when link is not publishable" do
before do
allow_any_instance_of(Link).to receive(:publishable?) { false }
end
it "returns an error message" do
post :publish, params: { id: @disabled_link.unique_permalink }
expect(response.parsed_body["error_message"]).to eq("You must connect at least one payment method before you can publish this product for sale.")
end
it "does not publish the link" do
post :publish, params: { id: @disabled_link.unique_permalink }
expect(response.parsed_body["success"]).to eq(false)
expect(@disabled_link.reload.purchase_disabled_at).to be_present
end
end
context "when user email is not confirmed" do
before do
seller.update!(confirmed_at: nil)
@unpublished_product = create(:physical_product, purchase_disabled_at: Time.current, user: seller)
end
it "returns an error message" do
post :publish, params: { id: @unpublished_product.unique_permalink }
expect(response.parsed_body["error_message"]).to eq("You have to confirm your email address before you can do that.")
end
it "does not publish the link" do
post :publish, params: { id: @unpublished_product.unique_permalink }
expect(response.parsed_body["success"]).to eq(false)
expect(@unpublished_product.reload.purchase_disabled_at).to be_present
end
end
context "when an unknown exception is raised" do
before do
allow_any_instance_of(Link).to receive(:publish!).and_raise("error")
end
it "sends a Bugsnag notification" do
expect(Bugsnag).to receive(:notify).once
post :publish, params: { id: @disabled_link.unique_permalink }
end
it "returns an error message" do
post :publish, params: { id: @disabled_link.unique_permalink }
expect(response.parsed_body["error_message"]).to eq("Something broke. We're looking into what happened. Sorry about this!")
end
it "does not publish the link" do
post :publish, params: { id: @disabled_link.unique_permalink }
expect(response.parsed_body["success"]).to eq(false)
expect(@disabled_link.reload.purchase_disabled_at).to be_present
end
end
end
describe "POST unpublish" do
it_behaves_like "collaborator can access", :post, :unpublish do
let(:product) { create(:product, user: seller) }
let(:request_params) { { id: product.unique_permalink } }
let(:response_attributes) { { "success" => true } }
end
end
describe "PUT sections" do
let(:product) { create(:product, user: seller) }
it_behaves_like "authorize called for action", :put, :update_sections do
let(:record) { product }
let(:request_params) { { id: product.unique_permalink } }
end
it_behaves_like "collaborator can access", :put, :update_sections do
let(:response_status) { 204 }
let(:request_params) { { id: product.unique_permalink } }
end
it "updates the SellerProfileSections attached to the product and cleans up orphaned sections" do
sections = create_list(:seller_profile_products_section, 2, seller:, product:)
create(:seller_profile_posts_section, seller:, product:)
create(:seller_profile_posts_section, seller:)
put :update_sections, params: { id: product.unique_permalink, sections: sections.map(&:external_id), main_section_index: 1 }
expect(product.reload).to have_attributes(sections: sections.map(&:id), main_section_index: 1)
expect(seller.seller_profile_sections.count).to eq 3
expect(seller.seller_profile_sections.on_profile.count).to eq 1
end
end
describe "DELETE destroy" do
describe "suspended tos violation user" do
before do
@admin_user = create(:user)
@product = create(:product, user: seller)
seller.flag_for_tos_violation(author_id: @admin_user.id, product_id: @product.id)
seller.suspend_for_tos_violation(author_id: @admin_user.id)
# NOTE: The invalidate_active_sessions! callback from suspending the user, interferes
# with the login mechanism, this is a hack get the `sign_in user` method work correctly
request.env["warden"].session["last_sign_in_at"] = DateTime.current.to_i
end
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { @product }
let(:request_params) { { id: @product.unique_permalink } }
end
it "allows deletion if user suspended (tos)" do
delete :destroy, params: { id: @product.unique_permalink }
expect(@product.reload.deleted_at.present?).to be(true)
end
end
end
describe "GET edit" do
let(:product) { create(:product, user: seller) }
it_behaves_like "authorize called for action", :get, :edit do
let(:record) { product }
let(:request_params) { { id: product.unique_permalink } }
end
it "assigns the correct instance variables" do
get :edit, params: { id: product.unique_permalink }
expect(response).to be_successful
product_presenter = assigns(:presenter)
expect(product_presenter.product).to eq(product)
expect(product_presenter.pundit_user).to eq(controller.pundit_user)
end
context "with other user not owning the product" do
let(:other_user) { create(:user) }
before do
sign_in other_user
end
it "redirects to product page" do
get :edit, params: { id: product.unique_permalink }
expect(response).to redirect_to(short_link_path(product))
end
end
context "with admin user signed in" do
let(:admin) { create(:admin_user) }
before do
sign_in admin
end
it "renders the page" do
get :edit, params: { id: product.unique_permalink }
expect(response).to have_http_status(:ok)
end
end
context "when the product is a bundle" do
let(:bundle) { create(:product, :bundle) }
it "redirects to the bundle edit page" do
sign_in bundle.user
get :edit, params: { id: bundle.unique_permalink }
expect(response).to redirect_to(bundle_path(bundle.external_id))
end
end
end
describe "PUT update" do
before do
@product = create(:product_with_pdf_file, user: seller)
@gif_file = fixture_file_upload("test-small.gif", "image/gif")
product_file = @product.product_files.alive.first
@params = {
id: @product.unique_permalink,
name: "sumlink",
description: "New description",
custom_button_text_option: "pay_prompt",
custom_summary: "summary",
custom_view_content_button_text: "Get Your Files",
custom_receipt_text: "Thank you for purchasing! Feel free to contact us any time for support.",
custom_attributes: [
{
name: "name",
value: "value"
},
],
file_attributes: [
{
name: "Length",
value: "10 sections"
}
],
files: [
{
id: product_file.external_id,
url: product_file.url
}
],
product_refund_policy_enabled: true,
refund_policy: {
max_refund_period_in_days: 7,
fine_print: "Sample fine print",
},
}
end
it_behaves_like "authorize called for action", :put, :update do
let(:record) { @product }
let(:request_params) { @params }
end
it_behaves_like "collaborator can access", :put, :update do
let(:product) { @product }
let(:request_params) { @params }
let(:response_status) { 204 }
end
context "when user email is empty" do
before do
seller.email = ""
seller.save(validate: false)
end
it "includes error_message when publishing" do
post :publish, params: { id: @product.unique_permalink }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["error_message"]).to eq("<span>To publish a product, we need you to have an email. <a href=\"#{settings_main_url}\">Set an email</a> to continue.</span>")
end
end
describe "licenses" do
context "when license key is embedded in the product-level rich content" do
it "sets is_licensed to true" do
expect(@product.is_licensed).to be(false)
post :update, params: @params.merge({ rich_content: [{ id: nil, title: "Page title", description: { type: "doc", content: [{ "type" => "licenseKey" }] } }] }), format: :json
expect(@product.reload.is_licensed).to be(true)
end
end
context "when license key is embedded in the rich content of at least one version" do
it "sets is_licensed to true" do
category = create(:variant_category, link: @product, title: "Versions")
version1 = create(:variant, variant_category: category, name: "Version 1")
version2 = create(:variant, variant_category: category, name: "Version 2")
version1_rich_content1 = create(:rich_content, entity: version1, description: [{ "type" => "paragraph", "content" => [{ "type" => "text", "text" => "Hello" }] }])
version1_rich_content1_updated_description = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Hello" }] }, { type: "licenseKey" }] }
version2_new_rich_content_description = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Newly added version 2 content" }] }] }
expect(@product.is_licensed).to be(false)
post :update, params: @params.merge({
variants: [
{ id: version1.external_id, name: version1.name, rich_content: [{ id: version1_rich_content1.external_id, title: "Version 1 - Page 1", description: version1_rich_content1_updated_description }] },
{ id: version2.external_id, name: version2.name, rich_content: [{ id: nil, title: "Version 2 - Page 1", description: version2_new_rich_content_description }] }]
}), format: :json
expect(@product.reload.is_licensed).to be(true)
end
end
it "sets is_licensed to false when no license key is embedded in the rich content" do
expect(@product.is_licensed).to be(false)
post :update, params: @params.merge({
rich_content: [{ id: nil, title: "Page title", description: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Hello" }] }] } }]
}), format: :json
expect(@product.reload.is_licensed).to be(false)
end
end
describe "coffee products" do
it "sets suggested_price_cents to the maximum price_difference_cents of variants" do
coffee_product = create(:coffee_product)
sign_in coffee_product.user
post :update, params: {
id: coffee_product.unique_permalink,
variants: [
{ price_difference_cents: 300 },
{ price_difference_cents: 500 },
{ price_difference_cents: 100 }
]
}, as: :json
expect(response).to be_successful
expect(coffee_product.reload.suggested_price_cents).to eq(500)
end
end
describe "content_updated_at" do
it "is updated when a new file is uploaded" do
freeze_time do
url = "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png"
post(:update, params: @params.merge!(files: [{ id: SecureRandom.uuid, url: }]), format: :json)
@product.reload
expect(@product.content_updated_at).to eq Time.current
end
end
it "is not updated when irrelevant attributes are changed" do
freeze_time do
post(:update, params: @params.merge(description: "new description"), format: :json)
expect(response).to be_successful
@product.reload
expect(@product.content_updated_at).to be_nil
end
end
end
describe "invalidate_action" do
before do
Rails.cache.write("views/#{@product.cache_key_prefix}_en_displayed_switch_ids_.html", "<html>hello</html>")
end
it "invalidates the action" do
expect(Rails.cache.read("views/#{@product.cache_key_prefix}_en_displayed_switch_ids_.html")).to_not be_nil
post :update, params: @params.merge({ id: @product.unique_permalink })
expect(Rails.cache.read("views/#{@product.cache_key_prefix}_en_displayed_switch_ids_.html")).to be_nil
end
end
it "updates the product" do
expect(SaveContentUpsellsService).to receive(:new).with(
seller: @product.user,
content: "New description",
old_content: "This is a collection of works spanning 1984 — 1994, while I spent time in a shack in the Andes.",
).and_call_original
put :update, params: @params, as: :json
expect(@product.reload.name).to eq "sumlink"
expect(@product.custom_button_text_option).to eq "pay_prompt"
expect(@product.custom_summary).to eq "summary"
expect(@product.custom_view_content_button_text).to eq "Get Your Files"
expect(@product.custom_receipt_text).to eq "Thank you for purchasing! Feel free to contact us any time for support."
expect(@product.custom_attributes).to eq [{ "name" => "name", "value" => "value" }]
expect(@product.removed_file_info_attributes).to eq [:Size]
expect(@product.product_refund_policy_enabled).to be(false)
expect(@product.product_refund_policy).to be_nil
end
context "when seller_refund_policy_disabled_for_all feature flag is set to true" do
before do
Feature.activate(:seller_refund_policy_disabled_for_all)
end
it "updates the product refund policy" do
put :update, params: @params, as: :json
@product.reload
expect(@product.product_refund_policy_enabled).to be(true)
expect(@product.product_refund_policy.title).to eq("7-day money back guarantee")
expect(@product.product_refund_policy.fine_print).to eq("Sample fine print")
end
end
context "when seller refund policy is set to false" do
before do
@product.user.update!(refund_policy_enabled: false)
end
it "updates the product refund policy" do
put :update, params: @params, as: :json
@product.reload
expect(@product.product_refund_policy_enabled).to be(true)
expect(@product.product_refund_policy.title).to eq "7-day money back guarantee"
expect(@product.product_refund_policy.fine_print).to eq "Sample fine print"
end
context "with product refund policy enabled" do
before do
@product.update!(product_refund_policy_enabled: true)
end
it "disables the product refund policy" do
@params[:product_refund_policy_enabled] = false
put :update, params: @params, as: :json
@product.reload
expect(@product.product_refund_policy_enabled).to be(false)
expect(@product.product_refund_policy).to be_nil
end
end
end
it "updates a physical product" do
product = create(:physical_product, user: seller, skus_enabled: true)
shipping_destination = product.shipping_destinations.first
post :update, params: {
id: product.unique_permalink,
name: "physical",
shipping_destinations: [
{
id: shipping_destination.id,
country_code: shipping_destination.country_code,
one_item_rate_cents: shipping_destination.one_item_rate_cents,
multiple_items_rate_cents: shipping_destination.multiple_items_rate_cents
}
]
}
expect(response).to be_successful
product.reload
expect(product.name).to eq "physical"
expect(product.skus_enabled).to be(false)
end
it "appends removed_file_info_attributes when additional keys are provided" do
put :update, params: @params.merge({ file_attributes: [] }), format: :json
expect(@product.reload.removed_file_info_attributes).to eq %i[Size Length]
end
describe "currency and price updates" do
before do
@product.update!(price_currency_type: "usd", price_cents: 1000)
end
it "changes product from USD $10 to EUR €12 and back to USD $11" do
expect(@product.price_currency_type).to eq "usd"
expect(@product.price_cents).to eq 1000
put :update, params: {
id: @product.unique_permalink,
price_currency_type: "eur",
price_cents: 1200
}, as: :json
expect(response).to be_successful
@product.reload
expect(@product.price_currency_type).to eq "eur"
expect(@product.price_cents).to eq 1200
put :update, params: {
id: @product.unique_permalink,
price_currency_type: "usd",
price_cents: 1100
}, as: :json
expect(response).to be_successful
@product.reload
expect(@product.price_currency_type).to eq "usd"
expect(@product.price_cents).to eq 1100
end
end
it "sets the correct value for removed_file_info_attributes if there are none" do
post :update, params: @params.merge({
file_attributes: [
{
name: "Length",
value: "10 sections"
},
{
name: "Size",
value: "100 TB"
}
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/product_review_responses_controller_spec.rb | spec/controllers/product_review_responses_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe ProductReviewResponsesController do
describe "PUT update" do
let!(:seller) { create(:named_seller) }
let!(:product) { create(:product, user: seller) }
let!(:purchaser) { create(:user) }
let!(:purchase) { create(:purchase, link: product, purchaser: purchaser) }
let!(:product_review) { create(:product_review, purchase: purchase) }
let(:product_review_for_another_seller) { create(:product_review) }
before do
sign_in seller
end
it_behaves_like "authorize called for action", :put, :update do
let(:record) { ProductReviewResponse }
let(:policy_klass) { ProductReviewResponsePolicy }
let(:request_params) { { id: purchase.external_id, message: "Response" } }
let(:request_format) { :json }
end
it "creates a new response if there is none" do
product_review.response&.destroy!
put :update, params: { id: purchase.external_id, message: "New" }, as: :json
expect(response).to have_http_status(:no_content)
product_review.reload
expect(product_review.response.message).to eq("New")
expect(product_review.response.user_id).to eq(seller.id)
end
it "updates an existing response if there is one, regardless of who the original author is" do
different_user = create(:user)
review_response = create(:product_review_response, message: "Old", product_review:, user: different_user)
put :update, params: { id: purchase.external_id, message: "Updated" }, as: :json
expect(response).to have_http_status(:no_content)
review_response.reload
expect(review_response.product_review).to eq(product_review)
expect(review_response.message).to eq("Updated")
expect(review_response.user_id).to eq(seller.id)
end
it "allows responding to reviews that do not count towards review stats" do
purchase.update!(stripe_refunded: true)
expect(purchase.allows_review_to_be_counted?).to be false
put :update, params: { id: purchase.external_id, message: "Review response" }, as: :json
expect(response).to have_http_status(:no_content)
product_review.reload
expect(product_review.response.message).to eq("Review response")
expect(product_review.response.user_id).to eq(seller.id)
end
it "returns an error if the message is blank" do
put :update, params: { id: purchase.external_id, message: "" }, as: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body["error"]).to eq("Message can't be blank")
end
it "404s for non-existent purchase" do
expect do
put :update, params: { id: "non_existent_id", message: "Updated" }, as: :json
end.to raise_error(ActionController::RoutingError, "Not Found")
end
it "404s when there is no product review" do
product_review.delete
put :update, params: { id: purchase.external_id, message: "Updated" }, as: :json
expect(response).to have_http_status(:not_found)
end
it "401s when the product review is for another seller" do
put :update, params: {
id: product_review_for_another_seller.purchase.external_id,
message: "Updated",
}, as: :json
expect(response).to have_http_status(:unauthorized)
end
end
describe "DELETE destroy" do
let!(:seller) { create(:named_seller) }
let!(:product) { create(:product, user: seller) }
let!(:purchaser) { create(:user) }
let!(:purchase) { create(:purchase, link: product, purchaser: purchaser) }
let!(:product_review) { create(:product_review, purchase: purchase) }
let!(:product_review_response) { create(:product_review_response, product_review: product_review) }
let(:product_review_for_another_seller) { create(:product_review) }
before do
sign_in seller
end
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { ProductReviewResponse }
let(:policy_klass) { ProductReviewResponsePolicy }
let(:request_params) { { id: purchase.external_id } }
let(:request_format) { :json }
end
it "destroys the response" do
delete :destroy, params: { id: purchase.external_id }, as: :json
expect(response).to have_http_status(:no_content)
product_review.reload
expect(product_review.response).to be_nil
end
it "404s for non-existent purchase" do
expect do
delete :destroy, params: { id: "non_existent_id" }, as: :json
end.to raise_error(ActionController::RoutingError, "Not Found")
end
it "404s when there is no product review" do
product_review.delete
delete :destroy, params: { id: purchase.external_id }, as: :json
expect(response).to have_http_status(:not_found)
end
it "401s when the product review is for another seller" do
delete :destroy, params: {
id: product_review_for_another_seller.purchase.external_id,
}, as: :json
expect(response).to have_http_status(:unauthorized)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/reviews_controller_spec.rb | spec/controllers/reviews_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe ReviewsController, type: :controller, inertia: true do
let(:user) { create(:user) }
describe "GET index" do
before do
Feature.activate(:reviews_page)
sign_in(user)
end
it_behaves_like "authorize called for action", :get, :index do
let(:record) { ProductReview }
end
it "renders the Inertia component with correct props" do
product = create(:product, price_cents: 0)
purchase_with_review = create(:free_purchase, :with_review, link: product)
purchase_with_review.update!(purchaser: user, email: user.email)
review = purchase_with_review.product_review
product_without_review = create(:product, price_cents: 0)
purchase_without_review = create(:free_purchase, link: product_without_review)
purchase_without_review.update!(purchaser: user, email: user.email)
expect(ReviewsPresenter).to receive(:new).with(user).and_call_original
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Reviews/Index")
expect(inertia.props[:reviews]).to be_an(Array)
review_props = inertia.props[:reviews].first
expect(review_props).to include(
id: review.external_id,
rating: review.rating,
message: review.message,
purchase_id: ObfuscateIds.encrypt(review.purchase_id),
purchase_email_digest: purchase_with_review.email_digest
)
expect(review_props).to have_key(:video)
expect(review_props[:video]).to be_in([nil, a_hash_including(:id, :thumbnail_url)])
expect(review_props[:product]).to include(
name: product.name,
url: product.long_url(recommended_by: "library"),
permalink: product.unique_permalink,
thumbnail_url: product.thumbnail_alive&.url,
native_type: product.native_type
)
expect(review_props[:product][:seller]).to include(
name: product.user.display_name,
url: product.user.profile_url
)
expect(inertia.props[:purchases]).to be_an(Array)
purchase_props = inertia.props[:purchases].find { |p| p[:id] == purchase_without_review.external_id }
expect(purchase_props).to be_present
expect(purchase_props).to include(
id: purchase_without_review.external_id,
email_digest: purchase_without_review.email_digest
)
expect(purchase_props[:product]).to include(
name: product_without_review.name,
url: product_without_review.long_url(recommended_by: "library"),
permalink: product_without_review.unique_permalink,
thumbnail_url: product_without_review.thumbnail_alive&.url,
native_type: product_without_review.native_type
)
expect(purchase_props[:product][:seller]).to include(
name: product_without_review.user.display_name,
url: product_without_review.user.profile_url
)
expect(inertia.props[:following_wishlists_enabled]).to be_in([true, false])
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/emails_controller_spec.rb | spec/controllers/emails_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/sellers_base_controller_concern"
require "inertia_rails/rspec"
describe EmailsController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
render_views
let(:seller) { create(:user) }
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Installment }
end
it "redirects to the published tab" do
get :index
expect(response).to redirect_to(published_emails_path)
end
it "redirects to the scheduled tab if there are scheduled installments" do
create(:scheduled_installment, seller:)
get :index
expect(response).to redirect_to(scheduled_emails_path)
end
end
describe "GET published" do
it_behaves_like "authorize called for action", :get, :published do
let(:record) { Installment }
let(:policy_method) { :index? }
end
it "renders the Inertia component with correct props" do
create(:installment, seller:, published_at: 1.day.ago)
get :published
expect(response).to be_successful
expect(inertia.component).to eq("Emails/Published")
expect(inertia.props).to include(
installments: be_an(Array),
pagination: be_a(Hash),
has_posts: be_in([true, false])
)
end
end
describe "GET scheduled" do
it_behaves_like "authorize called for action", :get, :scheduled do
let(:record) { Installment }
let(:policy_method) { :index? }
end
it "renders the Inertia component with correct props" do
create(:scheduled_installment, seller:)
get :scheduled
expect(response).to be_successful
expect(inertia.component).to eq("Emails/Scheduled")
expect(inertia.props).to include(
installments: be_an(Array),
pagination: be_a(Hash),
has_posts: be_in([true, false])
)
end
end
describe "GET drafts" do
it_behaves_like "authorize called for action", :get, :drafts do
let(:record) { Installment }
let(:policy_method) { :index? }
end
it "renders the Inertia component with correct props" do
create(:installment, seller:)
get :drafts
expect(response).to be_successful
expect(inertia.component).to eq("Emails/Drafts")
expect(inertia.props).to include(
installments: be_an(Array),
pagination: be_a(Hash),
has_posts: be_in([true, false])
)
end
end
describe "GET new" do
it_behaves_like "authorize called for action", :get, :new do
let(:record) { Installment }
end
it "renders the Inertia component with correct props" do
get :new
expect(response).to be_successful
expect(inertia.component).to eq("Emails/New")
expect(inertia.props).to have_key(:context)
end
it "includes copy_from installment when copy_from param is present" do
installment = create(:installment, seller:)
get :new, params: { copy_from: installment.external_id }
expect(response).to be_successful
expect(inertia.props).to have_key(:installment)
end
end
describe "GET edit" do
let(:installment) { create(:installment, seller:) }
it_behaves_like "authorize called for action", :get, :edit do
let(:record) { installment }
let(:request_params) { { id: installment.external_id } }
end
it "renders the Inertia component with correct props" do
get :edit, params: { id: installment.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Emails/Edit")
expect(inertia.props).to have_key(:installment)
expect(inertia.props).to have_key(:context)
end
context "when installment doesn't exist" do
it "returns 404" do
expect { get :edit, params: { id: "nonexistent" } }.to raise_error(ActionController::RoutingError)
end
end
end
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:record) { Installment }
let(:request_params) { { installment: { subject: "Test Email" } } }
end
context "when save is successful" do
let(:new_installment) { build(:installment, seller:) }
before do
allow_any_instance_of(SaveInstallmentService).to receive(:process).and_return(true)
allow_any_instance_of(SaveInstallmentService).to receive(:installment).and_return(new_installment)
end
it "redirects to edit email path with success notice" do
post :create, params: { installment: { subject: "Test Email" } }
expect(response).to redirect_to(edit_email_path(new_installment.external_id))
expect(flash[:notice]).to eq("Email created!")
end
it "redirects to edit path when save_and_preview_post is clicked" do
installment = create(:installment, seller:)
allow_any_instance_of(SaveInstallmentService).to receive(:installment).and_return(installment)
post :create, params: { installment: { subject: "Test Email" }, save_action_name: "save_and_preview_post" }
expect(response).to redirect_to(edit_email_path(installment.external_id, preview_post: true))
expect(flash[:notice]).to eq("Preview link opened.")
end
end
context "when save fails" do
before do
allow_any_instance_of(SaveInstallmentService).to receive(:process).and_return(false)
allow_any_instance_of(SaveInstallmentService).to receive(:error).and_return("Something went wrong")
end
it "redirects to new email path with alert" do
post :create, params: { installment: { subject: "Test Email" } }
expect(response).to redirect_to(new_email_path)
expect(flash[:alert]).to eq("Something went wrong")
end
end
end
describe "PATCH update" do
let(:installment) { create(:installment, seller:) }
it_behaves_like "authorize called for action", :patch, :update do
let(:record) { installment }
let(:request_params) { { id: installment.external_id, installment: { subject: "Updated Email" } } }
end
context "when save is successful" do
before do
allow_any_instance_of(SaveInstallmentService).to receive(:process).and_return(true)
allow_any_instance_of(SaveInstallmentService).to receive(:installment).and_return(installment)
end
it "redirects to edit email path with success notice" do
patch :update, params: { id: installment.external_id, installment: { subject: "Updated Email" } }
expect(response).to redirect_to(edit_email_path(installment.external_id))
expect(flash[:notice]).to eq("Changes saved!")
end
end
context "when save fails" do
before do
allow_any_instance_of(SaveInstallmentService).to receive(:process).and_return(false)
allow_any_instance_of(SaveInstallmentService).to receive(:error).and_return("Something went wrong")
end
it "redirects to edit email path with alert" do
patch :update, params: { id: installment.external_id, installment: { subject: "Updated Email" } }
expect(response).to redirect_to(edit_email_path(installment.external_id))
expect(flash[:alert]).to eq("Something went wrong")
end
end
end
describe "DELETE destroy" do
let!(:installment) { create(:installment, seller:) }
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { installment }
let(:request_params) { { id: installment.external_id } }
end
it "destroys the installment" do
expect do
delete :destroy, params: { id: installment.external_id }
end.to change(Installment.alive, :count).by(-1)
end
it "redirects to emails path with success notice" do
delete :destroy, params: { id: installment.external_id }
expect(response).to redirect_to(emails_path)
expect(flash[:notice]).to eq("Email deleted!")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/instant_payouts_controller_spec.rb | spec/controllers/instant_payouts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe InstantPayoutsController do
let(:seller) { create(:user) }
let(:instant_payouts_service) { instance_double(InstantPayoutsService) }
let(:date) { 1.day.ago.to_date }
before do
sign_in seller
allow(InstantPayoutsService).to receive(:new).with(seller, date:).and_return(instant_payouts_service)
end
describe "#create" do
context "when instant payout succeeds" do
before do
allow(instant_payouts_service).to receive(:perform).and_return({ success: true })
end
it "redirects to balance path with success notice" do
post :create, params: { date: }
expect(response).to redirect_to(balance_path)
expect(flash[:notice]).to eq("Instant payout initiated successfully")
end
end
context "when instant payout fails" do
before do
allow(instant_payouts_service).to receive(:perform).and_return(
{
success: false,
error: "Error message"
}
)
end
it "redirects to balance path with error alert" do
post :create, params: { date: }
expect(response).to redirect_to(balance_path)
expect(flash[:alert]).to eq("Error message")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/thumbnails_controller_spec.rb | spec/controllers/thumbnails_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe ThumbnailsController, :vcr do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
include_context "with user signed in as admin for seller"
describe "POST create" do
let(:blob) do
ActiveStorage::Blob.create_and_upload!(
io: fixture_file_upload("Austin's Mojo.png", "image/png"),
filename: "Austin's Mojo.png"
)
end
it_behaves_like "authorize called for action", :post, :create do
let(:record) { Thumbnail }
let(:request_params) { { link_id: product.unique_permalink, thumbnail: { signed_blob_id: blob.signed_id } } }
end
context "when signed in user is not the owner" do
before do
sign_in(create(:user))
end
it "raises RoutingError" do
expect do
expect do
post(:create, params: { link_id: product.unique_permalink, thumbnail: { signed_blob_id: blob.signed_id } })
end.to raise_error(ActionController::RoutingError, "Not Found")
end.to_not change { Thumbnail.count }
end
end
context "with using image file" do
it "fails for an invalid thumbnail" do
expect(product.thumbnail).to eq(nil)
invalid_blob = ActiveStorage::Blob.create_and_upload!(
io: fixture_file_upload("test-squashed.png", "image/png"),
filename: "test-squashed.png"
)
expect do
post(:create, params: { link_id: product.unique_permalink, thumbnail: { signed_blob_id: invalid_blob.signed_id }, format: :json })
end.to change { Thumbnail.count }.by(0)
expect(product.reload.thumbnail).to eq(nil)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false, "error" => "Please upload a square thumbnail." })
end
it "creates a thumbnail" do
expect(product.thumbnail).to eq(nil)
expect do
post(:create, params: { link_id: product.unique_permalink, thumbnail: { signed_blob_id: blob.signed_id }, format: :json })
end.to change { Thumbnail.count }.by(1)
expect(product.reload.thumbnail.file.blob).to eq(blob)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "thumbnail" => product.thumbnail.as_json.stringify_keys })
end
it "modifies thumbnail if one created from file already exists" do
product.update!(thumbnail: create(:thumbnail))
expect do
post(:create, params: { link_id: product.unique_permalink, thumbnail: { signed_blob_id: blob.signed_id }, format: :json })
end.to change { Thumbnail.count }.by(0)
expect(product.reload.thumbnail.file.blob).to eq(blob)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "thumbnail" => product.thumbnail.as_json.stringify_keys })
end
end
it "restores deleted thumbnail if exists" do
product.update!(thumbnail: create(:thumbnail))
product.thumbnail.mark_deleted!
expect do
post(:create, params: { link_id: product.unique_permalink, thumbnail: { signed_blob_id: blob.signed_id }, format: :json })
end.to change { Thumbnail.alive.count }.by(1)
.and change { Thumbnail.count }.by(0)
.and change { product.reload.thumbnail.deleted? }.from(true).to(false)
expect(product.reload.thumbnail.file.blob).to eq(blob)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "thumbnail" => product.thumbnail.as_json.stringify_keys })
end
end
describe "DELETE destroy" do
let(:product) { create(:thumbnail).product }
before do
sign_in(product.user)
end
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { Thumbnail }
let(:request_params) { { link_id: product.unique_permalink, id: product.thumbnail.guid } }
end
context "when logged in user is admin of seller account" do
let(:admin) { create(:user) }
before do
create(:team_membership, user: admin, seller: product.user, role: TeamMembership::ROLE_ADMIN)
cookies.encrypted[:current_seller_id] = product.user.id
sign_in admin
end
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { Thumbnail }
let(:request_params) { { link_id: product.unique_permalink, id: product.thumbnail.guid } }
end
end
it "fails if user is not the owner" do
sign_in(create(:user))
expect do
expect do
delete(:destroy, params: { link_id: product.unique_permalink, id: product.thumbnail.guid })
end.to raise_error(ActionController::RoutingError, "Not Found")
end.to_not change { Thumbnail.alive.count }
end
it "fails for an invalid thumbnail" do
expect do
delete(:destroy, params: { link_id: product.unique_permalink, id: "invalid_id" })
end.to_not change { Thumbnail.alive.count }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "removes the thumbnail" do
expect do
delete(:destroy, params: { link_id: product.unique_permalink, id: product.thumbnail.guid })
end.to change { Thumbnail.alive.count }.from(1).to(0)
.and change { product.reload.thumbnail.deleted? }.from(false).to(true)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "thumbnail" => product.thumbnail.as_json.stringify_keys })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/dropbox_files_controller_spec.rb | spec/controllers/dropbox_files_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe DropboxFilesController do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:policy_klass) { DropboxFilesPolicy }
let(:record) { :dropbox_files }
end
it "enqueues the job to transfer the file to S3" do
post :create, params: { link: "http://example.com/dropbox-url" }
expect(TransferDropboxFileToS3Worker).to have_enqueued_sidekiq_job(kind_of(Integer))
end
end
describe "GET index" do
let(:product) { create(:product, user: seller) }
let!(:dropbox_file) { create(:dropbox_file, link: product) }
it_behaves_like "authorize called for action", :get, :index do
let(:policy_klass) { DropboxFilesPolicy }
let(:record) { :dropbox_files }
end
it "returns available files for product" do
get :index, params: { link_id: product.unique_permalink }
expect(response.parsed_body["dropbox_files"]).to eq([dropbox_file.as_json.stringify_keys])
end
it "returns available files for user" do
dropbox_file = create(:dropbox_file, user: seller)
get :index
expect(response.parsed_body["dropbox_files"]).to eq([dropbox_file.as_json.stringify_keys])
end
end
describe "POST cancel_upload" do
let(:product) { create(:product, user: seller) }
let!(:dropbox_file) { create(:dropbox_file, link: product) }
it_behaves_like "authorize called for action", :post, :cancel_upload do
let(:policy_klass) { DropboxFilesPolicy }
let(:record) { :dropbox_files }
let(:request_params) { { id: dropbox_file.external_id } }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/wishlists_controller_spec.rb | spec/controllers/wishlists_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe WishlistsController, type: :controller, inertia: true do
let(:user) { create(:user) }
let(:wishlist) { create(:wishlist, user:) }
describe "GET index" do
before do
sign_in(user)
wishlist
end
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Wishlist }
end
context "when html is requested" do
it "renders Wishlists/Index with Inertia and non-deleted wishlists for the current seller" do
wishlist.mark_deleted!
alive_wishlist = create(:wishlist, user:)
create(:wishlist)
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Wishlists/Index")
expect(inertia.props[:wishlists]).to contain_exactly(a_hash_including(id: alive_wishlist.external_id))
end
end
context "when json is requested" do
it "returns wishlists with the given ids" do
wishlist2 = create(:wishlist, user:)
create(:wishlist, user:)
get :index, format: :json, params: { ids: [wishlist.external_id, wishlist2.external_id] }
expect(response).to be_successful
expect(response.parsed_body).to eq(WishlistPresenter.cards_props(wishlists: Wishlist.where(id: [wishlist.id, wishlist2.id]), pundit_user: controller.pundit_user, layout: Product::Layout::PROFILE).as_json)
end
end
end
describe "POST create" do
before do
sign_in user
end
it_behaves_like "authorize called for action", :post, :create do
let(:record) { Wishlist }
end
it "creates a wishlist with the given name" do
expect { post :create, format: :json, params: { wishlist: { name: "My Favorite Products" } } }
.to change(Wishlist, :count).by(1)
expect(Wishlist.last).to have_attributes(name: "My Favorite Products", user:)
expect(response.parsed_body).to eq(
"wishlist" => {
"id" => Wishlist.last.external_id,
"name" => "My Favorite Products"
}
)
end
it "returns an error when name is blank" do
expect { post :create, format: :json, params: { wishlist: { name: "" } } }
.not_to change(Wishlist, :count)
expect(response).to have_http_status(:unprocessable_entity)
end
it "creates a wishlist and redirects with notice" do
expect { post :create, params: { wishlist: { name: "My Wishlist" } } }
.to change(Wishlist, :count).by(1)
expect(response).to redirect_to(wishlists_path)
expect(flash[:notice]).to eq("Wishlist created!")
end
end
describe "GET show" do
it "renders Wishlists/Show with Inertia and public props" do
request.host = URI.parse(user.subdomain_with_protocol).host
get :show, params: { id: wishlist.url_slug }
expect(response).to be_successful
expect(inertia.component).to eq("Wishlists/Show")
expect(inertia.props[:id]).to eq(wishlist.external_id)
expect(inertia.props[:name]).to eq(wishlist.name)
expect(inertia.props[:layout]).to be_nil
end
context "when layout is profile" do
it "includes creator_profile in props" do
request.host = URI.parse(user.subdomain_with_protocol).host
get :show, params: { id: wishlist.url_slug, layout: "profile" }
expect(response).to be_successful
expect(inertia.component).to eq("Wishlists/Show")
expect(inertia.props[:layout]).to eq("profile")
expect(inertia.props[:creator_profile]).to be_present
end
end
context "when layout is discover" do
it "includes taxonomies_for_nav in props" do
request.host = URI.parse(user.subdomain_with_protocol).host
get :show, params: { id: wishlist.url_slug, layout: "discover" }
expect(response).to be_successful
expect(inertia.component).to eq("Wishlists/Show")
expect(inertia.props[:layout]).to eq("discover")
expect(inertia.props).to have_key(:taxonomies_for_nav)
end
end
context "when the wishlist is deleted" do
before { wishlist.mark_deleted! }
it "returns 404" do
request.host = URI.parse(user.subdomain_with_protocol).host
expect { get :show, params: { id: wishlist.url_slug } }.to raise_error(ActionController::RoutingError, "Not Found")
end
end
end
describe "PUT update" do
before do
sign_in(user)
end
it_behaves_like "authorize called for action", :put, :update do
let(:record) { Wishlist }
let(:request_params) { { id: wishlist.external_id, wishlist: { name: "New Name" } } }
end
it "updates the wishlist name and description" do
put :update, params: { id: wishlist.external_id, wishlist: { name: "New Name", description: "New Description" } }
expect(response).to redirect_to(wishlists_path)
expect(flash[:notice]).to eq("Wishlist updated!")
expect(wishlist.reload.name).to eq "New Name"
expect(wishlist.description).to eq "New Description"
end
it "renders validation errors" do
expect do
put :update, params: { id: wishlist.external_id, wishlist: { name: "" } }
end.not_to change { wishlist.reload.name }
expect(response).to redirect_to(wishlists_path)
expect(response).to have_http_status(:see_other)
end
end
describe "DELETE destroy" do
before do
sign_in(user)
end
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { wishlist }
let(:request_params) { { id: wishlist.external_id } }
end
it "marks the wishlist and followers as deleted" do
wishlist_follower = create(:wishlist_follower, wishlist:)
delete :destroy, params: { id: wishlist.external_id }
expect(response).to redirect_to(wishlists_path)
expect(flash[:notice]).to eq("Wishlist deleted!")
expect(wishlist.reload).to be_deleted
expect(wishlist_follower.reload).to be_deleted
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/url_redirects_controller_spec.rb | spec/controllers/url_redirects_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UrlRedirectsController do
render_views
before do
@product = create(:product_with_pdf_file)
@url_redirect = create(:url_redirect, purchase: create(:purchase, email: "abCabC@abc.com", link: @product))
@token = @url_redirect.token
@url = @url_redirect.referenced_link.product_files.alive.first.url
end
describe "GET 'download_page'" do
before do
# TODO: Uncomment after removing the :custom_domain_download feature flag (curtiseinsmann)
# @request.host = URI.parse(@product.user.subdomain_with_protocol).host
end
it "adds X-Robots-Tag response header to avoid page indexing" do
get :download_page, params: { id: @token }
expect(response.headers["X-Robots-Tag"]).to eq("noindex")
end
it "renders correctly" do
get :download_page, params: { id: @token }
expect(response).to be_successful
expect(assigns(:hide_layouts)).to eq(true)
expect(
assigns(:react_component_props)
).to eq(
UrlRedirectPresenter.new(
url_redirect: @url_redirect,
logged_in_user: nil
).download_page_with_content_props.merge(
is_mobile_app_web_view: false,
content_unavailability_reason_code: nil,
add_to_library_option: "signup_form"
)
)
end
context "with access revoked for purchase" do
before do
@url_redirect.purchase.update!(is_access_revoked: true)
end
it "redirects to expired page" do
expect do
get :download_page, params: { id: @token }
end.not_to change(ConsumptionEvent, :count)
expect(response).to redirect_to(url_redirect_expired_page_path(id: @url_redirect.token))
end
end
it "creates consumption event" do
expect do
get :download_page, params: { id: @token }
end.to change(ConsumptionEvent, :count).by(1)
expect(response).to be_successful
event = ConsumptionEvent.last
expect(event.event_type).to eq(ConsumptionEvent::EVENT_TYPE_VIEW)
expect(event.product_file_id).to be_nil
expect(event.url_redirect_id).to eq @url_redirect.id
expect(event.purchase_id).not_to be_nil
expect(event.link_id).to eq @product.id
expect(event.platform).to eq Platform::WEB
end
context "when mobile view param is passed" do
it "renders correctly" do
get :download_page, params: { id: @token, display: "mobile_app" }
expect(response).to be_successful
expect(assigns(:react_component_props)[:is_mobile_app_web_view]).to eq(true)
assert_select "h1", { text: @product.name, count: 0 }
assert_select "h4", { text: "Liked it? Give it a rating:", count: 0 }
assert_select "h4", { text: "Display Name", count: 1 }
assert_select "a", { text: "Download", count: 1 }
end
end
describe "licenses" do
before do
@seller = create(:user)
@product = create(:product, user: @seller, is_licensed: true)
@purchase = create(:purchase, link: @product, price_cents: 100, license: create(:license))
@url_redirect = create(:url_redirect, purchase: @purchase)
@token = @url_redirect.token
end
it "displays the license key for the purchase" do
get :download_page, params: { id: @token }
expect(response.body).to include @purchase.license.serial
end
end
context "posts" do
let(:url_redirect) { create(:url_redirect, purchase:) }
let(:token) { url_redirect.token }
let(:subject) { assigns(:react_component_props).dig(:content, :posts) }
context "for products" do
let(:seller) { create(:named_seller) }
let(:user) { create(:user) }
let(:product) { create(:product, user: seller, is_licensed: true) }
let(:purchase) { create(:purchase, purchaser: user, email: user.email, link: product, price_cents: 100, license: create(:license)) }
let(:installment_1) { create(:installment, link: purchase.link, published_at: Time.current) }
before do
create(:creator_contacting_customers_email_info, purchase:, installment: installment_1)
end
it "returns updates from that purchase" do
get :download_page, params: { id: token }
expect(response).to be_successful
expect(response.body).to include(installment_1.displayed_name)
end
it "returns updates from those other purchases if they've bought the same product multiple times" do
purchase_2 = create(:purchase, purchaser: user, email: user.email, link: purchase.link)
installment_2 = create(:installment, link: purchase.link, published_at: Time.current)
create(:creator_contacting_customers_email_info, purchase: purchase_2, installment: installment_2)
purchase_3 = create(:purchase, purchaser: user, email: user.email, link: purchase.link)
installment_3 = create(:installment, link: purchase.link, published_at: Time.current)
create(:creator_contacting_customers_email_info, purchase: purchase_3, installment: installment_3)
sign_in user
get :download_page, params: { id: token }
expect(response).to be_successful
expect(response.body).to include(installment_1.displayed_name)
expect(response.body).to include(installment_2.displayed_name)
expect(response.body).to include(installment_3.displayed_name)
end
it "does not break if the user has been sent a post for a product they have not purchased" do
# this should not occur, but has in the past
installment_2 = create(:installment, published_at: Time.current)
create(:creator_contacting_customers_email_info, purchase:, installment: installment_2)
get :download_page, params: { id: token }
expect(response).to be_successful
end
shared_examples "not returns post" do
let(:installment_2) { create(:installment, link: product, published_at: Time.current) }
before do
create(:creator_contacting_customers_email_info, purchase: purchase_1, installment: installment_2)
end
it "does not return posts" do
get :download_page, params: { id: token }
expect(subject).to match_array(a_hash_including(name: installment_1.name))
end
end
shared_examples "returns post" do
let(:installment_2) { create(:installment, link: product, published_at: Time.current) }
before do
create(:creator_contacting_customers_email_info, purchase: purchase_1, installment: installment_2)
end
it "does return posts" do
get :download_page, params: { id: token }
expect(subject).to match_array(
[
a_hash_including(name: installment_1.name),
a_hash_including(name: installment_2.name)
]
)
end
end
context "for not purchased products" do
let(:purchase_1) { create(:purchase, link: product) }
include_examples "not returns post"
end
context "for a failed product purchase" do
let(:purchase_1) { create(:failed_purchase, purchaser: user, email: user.email, link: product) }
include_examples "not returns post"
end
context "for a fully refunded product purchase" do
let(:purchase_1) { create(:refunded_purchase, purchaser: user, email: user.email, link: product) }
include_examples "not returns post"
end
context "for a chargedback product purchase" do
let(:purchase_1) { create(:purchase, purchaser: user, email: user.email, link: product, chargeback_date: Time.current) }
include_examples "not returns post"
end
context "for a gift sent purchase" do
let(:purchase_1) { create(:purchase, purchaser: user, email: user.email, link: product, is_gift_sender_purchase: true) }
include_examples "not returns post"
end
context "for a chargedback reversed purchase" do
let(:purchase_1) { create(:purchase, purchaser: user, email: user.email, link: product, chargeback_date: Time.current, chargeback_reversed: true) }
include_examples "returns post"
end
context "for a partially refunded purchase" do
let(:purchase_1) { create(:purchase, purchaser: user, email: user.email, link: product, stripe_partially_refunded: true) }
include_examples "returns post"
end
context "for a test purchase" do
let(:purchase_1) { create(:test_purchase, purchaser: user, email: user.email, link: product) }
include_examples "returns post"
end
context "for a received gift purchase" do
let(:purchase_1) { create(:purchase, purchaser: user, email: user.email, link: product, is_gift_receiver_purchase: true) }
include_examples "returns post"
end
end
context "for subscriptions", :vcr do
let(:product) { create(:subscription_product) }
let(:subscription) { create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: product) }
let(:purchase) do create(:purchase, link: product, email: subscription.user.email,
is_original_subscription_purchase: true,
subscription:, created_at: 2.days.ago) end
let(:installment) { create(:installment, link: purchase.link, published_at: 1.day.ago) }
before do
create(:creator_contacting_customers_email_info_sent, purchase:, installment:, sent_at: 1.hour.ago)
end
it "returns posts" do
get :download_page, params: { id: token }
expect(subject).to match_array(a_hash_including(name: installment.name))
end
context "when it is deactivated" do
let(:subscription) { create(:subscription, user: create(:user, credit_card: create(:credit_card)), link: product, deactivated_at: Time.current) }
context "and access is blocked on cancellation" do
let(:product) { create(:subscription_product, block_access_after_membership_cancellation: true) }
it "does not return posts" do
get :download_page, params: { id: token }
expect(subject).to be_empty
end
end
context "when access not blocked on cancellation" do
let(:product) { create(:subscription_product, block_access_after_membership_cancellation: false) }
it "does return posts" do
get :download_page, params: { id: token }
expect(subject).to match_array(a_hash_including(name: installment.name))
end
end
end
end
context "with a bundle purchase" do
let(:purchase) { create(:purchase, link: create(:product, :bundle), is_bundle_purchase: true) }
before do
purchase.create_url_redirect!
end
it "redirects to the library page without creating consumption event" do
expect do
get :download_page, params: { id: purchase.url_redirect.token }
end.not_to change(ConsumptionEvent, :count)
expect(response).to redirect_to(library_url({ bundles: purchase.link.external_id }))
end
context "when the url_redirect doesn't belong to a product" do
before do
# This seems to be the case for (some) purchases that have is_bundle_purchase set to true
# Production UrlRedirect record for reference: 314046200
purchase.url_redirect.update!(link: nil)
end
it "redirects to the library page" do
expect do
get :download_page, params: { id: purchase.url_redirect.token }
end.not_to change(ConsumptionEvent, :count)
expect(response).to redirect_to(library_url({ bundles: purchase.link.external_id }))
end
end
context "when the receipt parameter is present" do
it "includes the purchase_id parameter when redirecting" do
get :download_page, params: { id: purchase.url_redirect.token, receipt: true }
expect(response).to redirect_to(library_url({ bundles: purchase.link.external_id, purchase_id: purchase.external_id }))
end
end
end
end
describe "when user is signed in" do
before do
@user = create(:user, email: @url_redirect.purchase.email)
sign_in @user
end
describe "with purchase purchaser is nil" do
it "renders add to library" do
get :download_page, params: { id: @token }
expect(response.body).to include "Add to library"
end
end
describe "with purchase purchaser set to signed in user" do
before do
@url_redirect.purchase.purchaser = @user
@url_redirect.purchase.save!
end
it "does not render add to library" do
get :download_page, params: { id: @token }
expect(response.body).to_not include "Add to library"
end
end
it "redirects to check purchaser if signed in user is not purchaser" do
@url_redirect.purchase.purchaser = create(:user)
@url_redirect.purchase.save!
get :download_page, params: { id: @token }
expect(response).to redirect_to "#{url_redirect_check_purchaser_path(@url_redirect.token)}?next=#{CGI.escape request.path}"
end
end
describe "when user does not exist with purchase email" do
it "renders signup form" do
get :download_page, params: { id: @token }
expect(response.body).to_not include "Access this product from anywhere, forever:"
expect(response.body).to include "Create an account to access all of your purchases"
end
end
it "increments the view count on the url_redirect" do
expect { get :download_page, params: { id: @token } }.to change {
@url_redirect.reload.uses
}.by(1)
end
describe "installments" do
before do
@seller = create(:user)
@product = create(:product, user: @seller)
@seller_installment = create(:installment, seller: @seller, installment_type: "seller", link: nil)
@seller_installment.product_files.create!(url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/magic.mp3")
@url_redirect = create(:url_redirect, installment: @seller_installment, purchase: nil, link: @product)
@token = @url_redirect.token
allow_any_instance_of(Aws::S3::Object).to receive(:content_length).and_return(1_000_000)
travel_to(Time.current)
end
it "renders the download page properly for a product installment with files" do
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_product_files_path(@url_redirect.token, { product_file_ids: [ProductFile.last.external_id] })
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for a variant installment with files" do
category = create(:variant_category, link: @product, title: "Color")
variant = create(:variant, variant_category: category, name: "Blue")
@url_redirect.update(link: @product)
@seller_installment.update!(installment_type: Installment::VARIANT_TYPE, base_variant_id: variant.id)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_product_files_path(@url_redirect.token, { product_file_ids: [ProductFile.last.external_id] })
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for a follower installment with files" do
@seller_installment.update!(installment_type: Installment::FOLLOWER_TYPE)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_product_files_path(@url_redirect.token, { product_file_ids: [ProductFile.last.external_id] })
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for an affiliate installment with files" do
@seller_installment.update!(installment_type: Installment::AFFILIATE_TYPE)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_product_files_path(@url_redirect.token, { product_file_ids: [ProductFile.last.external_id] })
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for an audience installment with files" do
@seller_installment.update!(installment_type: Installment::AUDIENCE_TYPE)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_product_files_path(@url_redirect.token, { product_file_ids: [ProductFile.last.external_id] })
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for a membership installment that used to have files and now does not" do
@product.update!(is_recurring_billing: true)
@url_redirect.update!(link: @product)
@seller_installment.product_files.last.mark_deleted!
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_page_path(@token)
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "returns a 404 if the url redirect is not found" do
expect do
get :download_page, params: { id: "some non-existent id" }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 if the url redirect is for a membership installment that is now deleted" do
@product.update!(is_recurring_billing: true)
@url_redirect.update!(link: @product)
@seller_installment.mark_deleted!
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 if the url redirect is for a creator (not product) installment that is now deleted" do
@seller_installment.mark_deleted!
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "404s if the url redirect is for a creator (not product) installment that used to have files and now does not" do
@seller_installment.product_files.last.mark_deleted
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "renders the download page properly for a product installment without files that was purchased" do
@url_redirect.update(link: @product, purchase: create(:purchase, link: @product))
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::PRODUCT_TYPE, link: @product)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_page_path(@token)
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "renders the download page properly for a variant installment without files that was purchased" do
category = create(:variant_category, link: @product, title: "Color")
variant = create(:variant, variant_category: category, name: "Blue")
@url_redirect.update(link: @product, purchase: create(:purchase, link: @product))
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::VARIANT_TYPE, base_variant_id: variant.id)
get :download_page, params: { id: @token }
expect(response.body).to include url_redirect_download_page_path(@token)
expect(response.body).to_not have_selector(".product-related .preview-container")
end
it "returns 404 error if the url redirect is for a product installment without files and was not purchased" do
@url_redirect.update(link: @product)
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::PRODUCT_TYPE)
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 error if the url redirect is for a variant installment without files and was not purchased" do
category = create(:variant_category, link: @product, title: "Color")
variant = create(:variant, variant_category: category, name: "Blue")
@url_redirect.update(link: @product)
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::VARIANT_TYPE, base_variant_id: variant.id)
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 error if the url redirect is for a follower installment without files" do
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::FOLLOWER_TYPE)
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 error if the url redirect is for an affiliate installment without files" do
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::AFFILIATE_TYPE)
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 error if the url redirect is for an audience installment without files" do
@seller_installment.product_files.last.mark_deleted
@seller_installment.update!(installment_type: Installment::AUDIENCE_TYPE)
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 error if the url redirect is for a physical product installment that used to have files and now does not" do
@product.is_physical = true
# bypassing physical product validations.
@product.update_column(:flags, @product.flags)
@seller_installment.link = @product
@seller_installment.save!
@seller_installment.product_files.last.mark_deleted
expect do
get :download_page, params: { id: @token }
end.to raise_error(ActionController::RoutingError)
end
end
describe "streaming" do
before do
@product = create(:product_with_video_file)
@url_redirect = create(:url_redirect, link: @product, purchase: nil)
end
it "only increments uses once" do
expect { get :download_page, params: { id: @url_redirect.token } }.to change {
@url_redirect.reload.uses
}.by(1)
end
it "redirects to the expiration page if the rental has expired" do
@url_redirect.update(is_rental: true, rental_first_viewed_at: 10.days.ago)
@url_redirect.purchase = create(:purchase, is_rental: true)
@url_redirect.save!
ExpireRentalPurchasesWorker.new.perform
get :stream, params: { id: @url_redirect.token }
expect(response).to redirect_to(url_redirect_rental_expired_page_path(id: @url_redirect.token))
end
context "when 'product_file_id' is missing from the params" do
before do
@product.product_files << create(:product_file, link: @product)
stub_const("UrlRedirect::GUID_GETTER_FROM_S3_URL_REGEX", /(specs)/)
end
it "assigns the first streamable product file to '@product_file' and renders the stream page correctly" do
get :stream, params: { id: @url_redirect.token }
expect(response).to have_http_status(:ok)
expect(assigns(:product_file)).to eq(@product.product_files.first)
end
end
context "when there are no streamable files" do
before do
@product.product_files.each(&:mark_deleted!)
end
it "raises 404 error" do
expect do
get :stream, params: { id: @url_redirect.token, product_file_id: @product.product_files.first.external_id }
end.to raise_error(ActionController::RoutingError)
end
end
it "creates consumption event" do
@url_redirect.update!(purchase: create(:purchase, link: @product))
expect do
get :download_page, params: { id: @url_redirect.token }
end.to change(ConsumptionEvent, :count).by(1)
expect(response).to be_successful
event = ConsumptionEvent.last
expect(event.event_type).to eq(ConsumptionEvent::EVENT_TYPE_VIEW)
expect(event.product_file_id).to be_nil
expect(event.url_redirect_id).to eq @url_redirect.id
expect(event.purchase_id).not_to be_nil
expect(event.link_id).to eq @product.id
expect(event.platform).to eq Platform::WEB
end
end
describe "memberships" do
it "redirects to the expiration page if the membership inactive" do
product = create(:membership_product, price_cents: 100)
subscription = create(:subscription, link: product, user: create(:user), failed_at: Time.current)
purchase = create(:purchase, price_cents: 100, purchaser: subscription.user, link: product, subscription:, is_original_subscription_purchase: true)
product.update_attribute(:block_access_after_membership_cancellation, true)
url_redirect = create(:url_redirect, link: product, purchase:)
sign_in subscription.user
get :download_page, params: { id: url_redirect.token }
expect(response).to redirect_to(url_redirect_membership_inactive_page_path(id: url_redirect.token))
end
it "does not redirect to login page if no user signed in" do
product = create(:subscription_product, price_cents: 100)
subscription = create(:subscription, link: product, user: create(:user), failed_at: Time.current)
purchase = create(:purchase, price_cents: 100, purchaser: subscription.user, link: product, subscription:, is_original_subscription_purchase: true)
product.update_attribute(:block_access_after_membership_cancellation, true)
url_redirect = create(:url_redirect, link: product, purchase:)
get :download_page, params: { id: url_redirect.token }
expect(response).to_not redirect_to(login_url(next: request.path))
end
end
describe "needs to be confirmed" do
before do
@url_redirect = create(:url_redirect, uses: 1, has_been_seen: true, purchase: create(:purchase, email: "abCabC@abc.com"))
cookies.encrypted[:confirmed_redirect] = nil
@request.remote_ip = "123.4.5.6"
end
it "redirects to confirm page with correct parameters" do
get :download_page, params: { id: @url_redirect.token, display: "mobile_app" }
expect(response).to redirect_to(confirm_page_path(id: @url_redirect.token, destination: "download_page", display: "mobile_app"))
end
end
describe "coffee product" do
let(:url_redirect) { create(:url_redirect, purchase: create(:purchase, link: create(:coffee_product))) }
it "redirects to the coffee page and forwards the purchase_email parameter" do
get :download_page, params: { id: url_redirect.token, purchase_email: "test@gumroad.com" }
expect(response).to redirect_to(custom_domain_coffee_url(host: url_redirect.seller.subdomain_with_protocol, purchase_email: "test@gumroad.com"))
end
end
end
describe "GET download_archive" do
it "redirects to the download URL for the requested installment archive when the format is HTML" do
installment = create(:follower_installment, seller: create(:follower, follower_user_id: create(:user).id).user)
token = create(:installment_url_redirect, installment:).token
archive = installment.product_files_archives.new(product_files_archive_state: "ready")
archive.set_url_if_not_present
archive.save!
allow(controller).to(
receive(:signed_download_url_for_s3_key_and_filename)
.with(archive.s3_key, archive.s3_filename)
.and_return("https://example.com/the-entity-zip-url"))
get :download_archive, format: :html, params: { id: token }
expect(response).to redirect_to("https://example.com/the-entity-zip-url")
expect(ConsumptionEvent.where(event_type: ConsumptionEvent::EVENT_TYPE_DOWNLOAD_ALL).count).to eq(1)
end
it "returns the download URL for the requested folder archive" do
folder_id = SecureRandom.uuid
folder_archive = @url_redirect.product_files_archives.new(folder_id:, product_files_archive_state: "ready")
folder_archive.set_url_if_not_present
folder_archive.save!
get :download_archive, format: :json, params: { id: @token, folder_id: }
expect(response).to have_http_status(:success)
expect(response.parsed_body["url"]).to eq(url_redirect_download_archive_url(@token, folder_id:))
end
it "returns nil if the folder archive is not ready" do
folder_id = SecureRandom.uuid
folder_archive = @url_redirect.product_files_archives.new(folder_id:, product_files_archive_state: "queueing")
folder_archive.set_url_if_not_present
folder_archive.save!
get :download_archive, format: :json, params: { id: @token, folder_id: }
expect(response).to have_http_status(:success)
expect(response.parsed_body["url"]).to be_nil
end
it "redirects to the download URL for the requested entity archive when the format is HTML" do
entity_archive = @url_redirect.product_files_archives.new(product_files_archive_state: "ready")
entity_archive.set_url_if_not_present
entity_archive.save!
allow(controller).to(
receive(:signed_download_url_for_s3_key_and_filename)
.with(entity_archive.s3_key, entity_archive.s3_filename)
.and_return("https://example.com/the-entity-zip-url"))
get :download_archive, format: :html, params: { id: @token }
expect(response).to redirect_to("https://example.com/the-entity-zip-url")
expect(ConsumptionEvent.where(event_type: ConsumptionEvent::EVENT_TYPE_DOWNLOAD_ALL).count).to eq(1)
expect(ConsumptionEvent.where(event_type: ConsumptionEvent::EVENT_TYPE_FOLDER_DOWNLOAD).count).to eq(0)
end
it "redirects to the download URL for the requested folder archive when the format is HTML" do
folder_id = SecureRandom.uuid
folder_archive = @url_redirect.product_files_archives.new(folder_id:, product_files_archive_state: "ready")
folder_archive.set_url_if_not_present
folder_archive.save!
allow(controller).to(
receive(:signed_download_url_for_s3_key_and_filename)
.with(folder_archive.s3_key, folder_archive.s3_filename)
.and_return("https://example.com/the-folder-zip-url"))
get :download_archive, format: :html, params: { id: @token, folder_id: }
expect(response).to redirect_to("https://example.com/the-folder-zip-url")
expect(ConsumptionEvent.where(event_type: ConsumptionEvent::EVENT_TYPE_DOWNLOAD_ALL).count).to eq(0)
folder_events = ConsumptionEvent.where(event_type: ConsumptionEvent::EVENT_TYPE_FOLDER_DOWNLOAD)
expect(folder_events.count).to eq(1)
expect(folder_events.first.folder_id).to eq(folder_id)
end
end
describe "GET download_product_files" do
before do
@product = create(:product, user: create(:user))
@token = create(:url_redirect, purchase: create(:purchase, link: @product)).token
end
it "returns a 404 if no files exist" do
expect { get :download_product_files, format: :json, params: { product_file_ids: [], id: @token } }.to raise_error(ActionController::RoutingError)
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/product_duplicates_controller_spec.rb | spec/controllers/product_duplicates_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe ProductDuplicatesController do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:file_params) do
[
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/pencil.png" },
{ external_id: SecureRandom.uuid, url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/attachment/manual.pdf" }
]
end
include_context "with user signed in as admin for seller"
before do
product.save_files!(file_params)
end
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:request_params) { { id: product.unique_permalink } }
let(:record) { product }
let(:policy_klass) { ProductDuplicates::LinkPolicy }
end
it "returns 404 when the id parameter is missing" do
expect do
post :create
end.to raise_error(ActionController::RoutingError)
end
it "returns 404 when the id parameter is not the correct identifier for a product" do
expect do
post :create, params: { id: "invalid" }
end.to raise_error(ActionController::RoutingError)
end
it "returns success when the id parameter is the correct identifier for a product" do
post :create, params: { id: product.unique_permalink }
expect(product.reload.is_duplicating).to be(true)
expect(response.parsed_body["success"]).to be(true)
expect(response.parsed_body).not_to have_key("error_message")
end
it "returns an error message when the product is already duplicating" do
product.update!(is_duplicating: true)
post :create, params: { id: product.unique_permalink }
expect(response.parsed_body).to eq({ success: false, error_message: "Duplication in progress..." }.as_json)
end
it "queues DuplicateProductWorker when the id parameter is the correct identifier for a product" do
post :create, params: { id: product.unique_permalink }
expect(DuplicateProductWorker).to have_enqueued_sidekiq_job(product.id)
end
it "returns error_message when the current user is not the creator of the product" do
different_user = create(:user)
sign_in(different_user)
expect do
post :create, params: { id: product.unique_permalink }
end.to raise_error(ActionController::RoutingError)
end
end
describe "GET show" do
before do
product.update!(is_duplicating: false)
end
it_behaves_like "authorize called for action", :get, :show do
let(:request_params) { { id: product.unique_permalink } }
let(:record) { product }
let(:policy_klass) { ProductDuplicates::LinkPolicy }
end
it "returns an error message when the product is still duplicating" do
product.update!(is_duplicating: true)
get :show, params: { id: product.unique_permalink }
expect(response.parsed_body).to eq({ success: false, status: ProductDuplicatorService::DUPLICATING, error_message: "Duplication in progress..." }.as_json)
end
it "returns an error message when the product is not duplicating or recently duplicated" do
expect(ProductDuplicatorService.new(product.id).recently_duplicated_product).to be(nil)
get :show, params: { id: product.unique_permalink }
expect(response.parsed_body).to eq({ success: false, status: ProductDuplicatorService::DUPLICATION_FAILED }.as_json)
end
it "successfully returns a recently duplicated product" do
duplicated_product = ProductDuplicatorService.new(product.id).duplicate
duplicated_product = DashboardProductsPagePresenter.new(
pundit_user: SellerContext.new(user: user_with_role_for_seller, seller:),
memberships: [],
memberships_pagination: nil,
products: [duplicated_product],
products_pagination: nil
).page_props[:products].first
get :show, params: { id: product.unique_permalink }
expect(response.parsed_body).to eq({ success: true,
status: ProductDuplicatorService::DUPLICATED,
product:,
duplicated_product:,
is_membership: false }.as_json)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/library_controller_spec.rb | spec/controllers/library_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe LibraryController, :vcr, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:user) { create(:user) }
let(:policy_klass) { PurchasePolicy }
before do
sign_in user
end
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Purchase }
end
describe "normal products" do
let!(:visible_purchase) { create(:purchase, purchaser: user, link: create(:product, name: "Visible Product")) }
it "renders Library/Index with Inertia" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Library/Index")
expect(inertia.props[:results]).to be_an(Array)
expect(inertia.props[:results].map { |r| r.dig(:product, :name) }).to include("Visible Product")
end
it "doesn't show refunded purchases" do
refunded_purchase = create(:purchase, purchaser: user, link: create(:product, name: "Refunded Product"))
refunded_purchase.update_column(:stripe_refunded, true)
get :index
expect(response).to be_successful
product_names = inertia.props[:results].map { |r| r.dig(:product, :name) }
expect(product_names).to include("Visible Product")
expect(product_names).to_not include("Refunded Product")
end
it "doesn't show charged back purchases" do
chargeback_purchase = create(:purchase, purchaser: user, link: create(:product, name: "Chargeback Product"))
chargeback_purchase.update_column(:chargeback_date, Time.current)
get :index
expect(response).to be_successful
product_names = inertia.props[:results].map { |r| r.dig(:product, :name) }
expect(product_names).to include("Visible Product")
expect(product_names).to_not include("Chargeback Product")
end
it "doesn't show gift sender purchases" do
link = create(:product, name: "Product name")
purchase = create(:purchase, purchaser: user, link:, is_gift_sender_purchase: true)
create(:gift, gifter_email: "sahil@gumroad.com", giftee_email: "sahil2@gumroad.com", link_id: link.id, gifter_purchase_id: purchase.id)
get :index
expect(response).to be_successful
product_names = inertia.props[:results].map { |r| r.dig(:product, :name) }
expect(product_names).to_not include(link.name)
end
end
describe "failed webhooks" do
before do
@purchase = create(:purchase, url_redirect: nil, webhook_failed: true, purchaser: user)
end
it "renders successfully" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Library/Index")
end
end
context "when an unconfirmed user attempts to access the library" do
shared_examples "sends confirmation instructions" do
it "disallows access and sends confirmation instructions" do
allow(controller).to receive(:current_user).and_return(user)
expect(user).to receive(:send_confirmation_instructions)
get :index
expect(response).to redirect_to settings_main_path
expect(flash[:warning]).to eq("Please check your email to confirm your address before you can see that.")
end
end
before do
user.update_attribute(:confirmed_at, nil)
end
context "when no confirmation instructions were sent to user" do
before do
user.update_attribute(:confirmation_sent_at, nil)
end
it_behaves_like "sends confirmation instructions"
end
context "when previous confirmation instructions were sent more than 24 hours ago" do
before do
user.update_attribute(:confirmation_sent_at, 25.hours.ago)
end
it_behaves_like "sends confirmation instructions"
end
context "when confirmation instructions were sent within the last 24 hours" do
before do
user.update_attribute(:confirmation_sent_at, 5.hours.ago)
end
it "doesn't send duplicate confirmation instructions" do
allow(controller).to receive(:current_user).and_return(user)
expect(user).not_to receive(:send_confirmation_instructions)
get :index
end
end
end
describe "suspended (tos) user" do
before do
@admin_user = create(:user)
@product = create(:product, user:)
user.flag_for_tos_violation(author_id: @admin_user.id, product_id: @product.id)
user.suspend_for_tos_violation(author_id: @admin_user.id)
# NOTE: The invalidate_active_sessions! callback from suspending the user, interferes
# with the login mechanism, this is a hack get the `sign_in user` method work correctly
request.env["warden"].session["last_sign_in_at"] = DateTime.current.to_i
end
it "allows access" do
get :index
expect(response).to be_successful
end
end
describe "suspended (fraud) user" do
before do
@admin_user = create(:user)
user.flag_for_fraud(author_id: @admin_user.id)
user.suspend_for_fraud(author_id: @admin_user.id)
end
it "disallows access and redirects to the login page" do
get :index
expect(response).to redirect_to "/login"
end
end
end
describe "PATCH archive" do
let!(:purchase) { create(:purchase, purchaser: user) }
it_behaves_like "authorize called for action", :patch, :archive do
let(:record) { purchase }
let(:request_params) { { id: purchase.external_id } }
end
it "archives the purchase" do
expect do
patch :archive, params: { id: purchase.external_id }
expect(response).to redirect_to(library_path)
expect(flash[:notice]).to eq("Product archived!")
end.to change { purchase.reload.is_archived }.from(false).to(true)
end
end
describe "PATCH unarchive" do
let!(:purchase) { create(:purchase, purchaser: user, is_archived: true) }
it_behaves_like "authorize called for action", :patch, :unarchive do
let(:record) { purchase }
let(:request_params) { { id: purchase.external_id } }
end
it "unarchives the purchase" do
expect do
patch :unarchive, params: { id: purchase.external_id }
expect(response).to redirect_to(library_path)
expect(flash[:notice]).to eq("Product unarchived!")
end.to change { purchase.reload.is_archived }.from(true).to(false)
end
end
describe "PATCH delete" do
let!(:purchase) { create(:purchase, purchaser: user) }
it_behaves_like "authorize called for action", :patch, :delete do
let(:record) { purchase }
let(:request_params) { { id: purchase.external_id } }
end
it "deletes the purchase" do
expect do
patch :delete, params: { id: purchase.external_id }
expect(response).to redirect_to(library_path)
expect(flash[:notice]).to eq("Product deleted!")
end.to change { purchase.reload.is_deleted_by_buyer }.from(false).to(true)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/dashboard_controller_spec.rb | spec/controllers/dashboard_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe DashboardController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_user) }
before do
create(:user_compliance_info, user: seller, first_name: "Gumbot")
end
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { :dashboard }
end
def expect_dashboard_data_in_inertia_response(expected_data = {})
expect(inertia.props[:creator_home]).to be_present, "Expected creator_home in Inertia.js response"
expected_data.each do |key, value|
expect(inertia.props[:creator_home][key]).to eq(value), "Expected #{key} to be #{value}, but got #{inertia.props[:creator_home][key]}"
end
end
context "when seller has no activity" do
it "renders the page" do
get :index
expect(response).to be_successful
expect(response.body).to include("data-page")
expect(inertia).to render_component("Dashboard/Index")
expect_dashboard_data_in_inertia_response(
has_sale: false,
sales: [],
activity_items: []
)
end
it "creates LargeSeller record for sellers with many sales" do
stub_const("LargeSeller::SALES_LOWER_LIMIT", 0)
expect { get :index }.to change { LargeSeller.where(user: seller).count }.from(0).to(1)
end
end
context "when seller has products, but no sales" do
before do
create(:product, user: seller)
end
it "renders no sales text" do
get :index
expect(response).to be_successful
expect(inertia).to render_component("Dashboard/Index")
expect_dashboard_data_in_inertia_response(
has_sale: false
)
data_page_match = response.body.match(/data-page="([^"]*)"/)
decoded_content = CGI.unescapeHTML(data_page_match[1])
json_data = JSON.parse(decoded_content)
creator_home = json_data["props"]["creator_home"]
expect(creator_home["sales"]).to be_present
expect(creator_home["sales"].first["sales"]).to eq(0)
end
end
context "when seller has purchases" do
let(:product) { create(:product, user: seller, price_cents: 150) }
let(:follower) { create(:follower, user: seller, confirmed_at: 7.hours.ago) }
before do
create(:purchase_event, purchase: create(:purchase, link: product), created_at: Time.current)
follower.update!(confirmed_at: nil, deleted_at: 1.hour.ago)
end
around do |example|
travel_to Time.utc(2023, 6, 4) do
example.run
end
end
it "renders the purchase", :sidekiq_inline, :elasticsearch_wait_for_refresh do
get :index
expect(response).to be_successful
expect(inertia).to render_component("Dashboard/Index")
data_page_match = response.body.match(/data-page="([^"]*)"/)
if data_page_match
decoded_content = CGI.unescapeHTML(data_page_match[1])
json_data = JSON.parse(decoded_content)
creator_home = json_data["props"]["creator_home"]
puts "Creator home with purchases:"
puts " has_sale: #{creator_home['has_sale']}"
puts " sales count: #{creator_home['sales']&.length}"
puts " activity_items count: #{creator_home['activity_items']&.length}"
puts " balances: #{creator_home['balances']}"
puts " getting_started_stats: #{creator_home['getting_started_stats']}"
end
expect_dashboard_data_in_inertia_response(
has_sale: true
)
end
end
context "when seller has no alive products" do
let(:product) { create(:product, user: seller) }
before do
product.delete!
end
it "renders appropriate text" do
get :index
expect(response).to be_successful
# For Inertia.js, we should check for the data-page attribute and component name
expect(inertia).to render_component("Dashboard/Index")
# Check that the dashboard data shows no products (since product was deleted)
expect_dashboard_data_in_inertia_response(
has_sale: false,
sales: []
)
end
end
context "when seller has completed all 'Getting started' items" do
before do
create(:product, user: seller)
create(:workflow, seller:)
create(:active_follower, user: seller)
create(:purchase, :from_seller, seller:)
create(:payment_completed, user: seller)
create(:installment, seller:, send_emails: true)
small_bets_product = create(:product)
create(:purchase, purchaser: seller, link: small_bets_product)
stub_const("ENV", ENV.to_hash.merge("SMALL_BETS_PRODUCT_ID" => small_bets_product.id))
end
it "doesn't render `Getting started` text" do
get :index
expect(response.body).to_not have_text("We're here to help you get paid for your work.")
expect(response.body).to_not have_text("Getting started")
end
end
context "when seller is suspended for TOS" do
let(:admin_user) { create(:user) }
let!(:product) { create(:product, user: seller) }
before do
create(:user_compliance_info, user: seller)
seller.flag_for_tos_violation(author_id: admin_user.id, product_id: product.id)
seller.suspend_for_tos_violation(author_id: admin_user.id)
# NOTE: The invalidate_active_sessions! callback from suspending the user, interferes
# with the login mechanism, this is a hack get the `sign_in user` method work correctly
request.env["warden"].session["last_sign_in_at"] = DateTime.current.to_i
end
it "redirects to the products_path" do
get :index
expect(response).to redirect_to products_path
end
end
end
describe "GET customers_count" do
it_behaves_like "authorize called for action", :get, :customers_count do
let(:record) { :dashboard }
end
it "returns the formatted number of customers" do
allow_any_instance_of(User).to receive(:all_sales_count).and_return(123_456)
get :customers_count
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["value"]).to eq("123,456")
end
end
describe "GET total_revenue" do
it_behaves_like "authorize called for action", :get, :total_revenue do
let(:record) { :dashboard }
end
it "returns the formatted revenue" do
allow_any_instance_of(User).to receive(:gross_sales_cents_total_as_seller).and_return(123_456)
get :total_revenue
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["value"]).to eq("$1,234.56")
end
end
describe "GET active_members_count" do
it_behaves_like "authorize called for action", :get, :active_members_count do
let(:record) { :dashboard }
end
it "returns the formatted revenue" do
allow_any_instance_of(User).to receive(:active_members_count).and_return(123_456)
get :active_members_count
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["value"]).to eq("123,456")
end
end
describe "GET monthly_recurring_revenue" do
it_behaves_like "authorize called for action", :get, :monthly_recurring_revenue do
let(:record) { :dashboard }
end
it "returns the formatted revenue" do
allow_any_instance_of(User).to receive(:monthly_recurring_revenue).and_return(123_456)
get :monthly_recurring_revenue
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["value"]).to eq("$1,234.56")
end
end
describe "GET download_tax_form" do
it_behaves_like "authorize called for action", :get, :download_tax_form do
let(:record) { :dashboard }
end
it "redirects to the 1099 form download url if present" do
allow_any_instance_of(User).to receive(:tax_form_1099_download_url).and_return("https://gumroad.com/")
get :download_tax_form
expect(response).to redirect_to("https://gumroad.com/")
end
it "redirects to dashboard if form download url is not present" do
allow_any_instance_of(User).to receive(:tax_form_1099_download_url).and_return(nil)
get :download_tax_form
expect(response).to redirect_to(dashboard_url(host: UrlService.domain_with_protocol))
expect(flash[:alert]).to eq("A 1099 form for #{Time.current.prev_year.year} was not filed for your account.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/affiliates_controller_spec.rb | spec/controllers/affiliates_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/authentication_required"
require "inertia_rails/rspec"
describe AffiliatesController, type: :controller, inertia: true do
let(:seller) { create(:named_seller) }
let!(:product) { create(:product, user: seller) }
let(:affiliate_user) { create(:affiliate_user) }
context "within seller area" do
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authentication required for action", :get, :index
it_behaves_like "authorize called for action", :get, :index do
let(:record) { DirectAffiliate }
end
it "renders the affiliates page" do
create(:direct_affiliate, seller:, affiliate_user:)
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Affiliates/Index")
expect(inertia.props[:affiliates]).to be_present
end
context "when creator does not have any affiliates" do
it "redirects to the onboarding page" do
get :index
expect(response).to redirect_to(onboarding_affiliates_path)
end
end
end
describe "GET onboarding" do
it "renders the onboarding page" do
get :onboarding
expect(response).to be_successful
expect(inertia.component).to eq("Affiliates/Onboarding")
expect(inertia.props[:products]).to be_an(Array)
end
end
describe "GET new" do
it_behaves_like "authorize called for action", :get, :new do
let(:record) { DirectAffiliate }
let(:policy_method) { :create? }
end
it "renders the new affiliate page" do
get :new
expect(response).to be_successful
expect(inertia.component).to eq("Affiliates/New")
expect(inertia.props[:products]).to be_an(Array)
expect(inertia.props[:affiliates_disabled_reason]).to be_nil
end
end
describe "GET edit" do
let!(:affiliate) { create(:direct_affiliate, seller:, affiliate_user:) }
it_behaves_like "authorize called for action", :get, :edit do
let(:record) { affiliate }
let(:policy_method) { :update? }
let(:request_params) { { id: affiliate.external_id } }
end
it "renders the edit affiliate page" do
get :edit, params: { id: affiliate.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Affiliates/Edit")
expect(inertia.props[:affiliate][:id]).to eq(affiliate.external_id)
end
it "returns 404 for non-existent affiliate" do
expect { get :edit, params: { id: "nonexistent" } }.to raise_error(ActionController::RoutingError)
end
end
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:record) { DirectAffiliate }
let(:params) { { affiliate: { email: affiliate_user.email, fee_percent: 10, apply_to_all_products: true, products: [{ id: product.external_id_numeric, enabled: true }] } } }
end
it "creates an affiliate and redirects" do
post :create, params: { affiliate: { email: affiliate_user.email, fee_percent: 10, apply_to_all_products: true, products: [{ id: product.external_id_numeric, enabled: true }] } }
expect(response).to redirect_to(affiliates_path)
expect(flash[:notice]).to eq("Affiliate created successfully")
expect(seller.direct_affiliates.count).to eq(1)
end
it "redirects back with errors on invalid params" do
post :create, params: { affiliate: { email: "", fee_percent: 10, apply_to_all_products: true, products: [] } }
expect(response).to redirect_to(new_affiliate_path)
end
end
describe "PATCH update" do
let!(:affiliate) { create(:direct_affiliate, seller:, affiliate_user:) }
it_behaves_like "authorize called for action", :patch, :update do
let(:record) { affiliate }
let(:request_params) { { id: affiliate.external_id, affiliate: { email: affiliate_user.email, fee_percent: 15, apply_to_all_products: true, products: [{ id: product.external_id_numeric, enabled: true }] } } }
end
it "updates the affiliate and redirects" do
patch :update, params: { id: affiliate.external_id, affiliate: { email: affiliate_user.email, fee_percent: 15, apply_to_all_products: true, products: [{ id: product.external_id_numeric, enabled: true }] } }
expect(response).to redirect_to(affiliates_path)
expect(flash[:notice]).to eq("Affiliate updated successfully")
end
it "returns 404 for non-existent affiliate" do
expect { patch :update, params: { id: "nonexistent", affiliate: { email: affiliate_user.email } } }.to raise_error(ActionController::RoutingError)
end
end
describe "DELETE destroy" do
let!(:affiliate) { create(:direct_affiliate, seller:, affiliate_user:) }
it_behaves_like "authorize called for action", :delete, :destroy do
let(:record) { affiliate }
let(:request_params) { { id: affiliate.external_id } }
end
it "deletes the affiliate and redirects" do
delete :destroy, params: { id: affiliate.external_id }
expect(response).to redirect_to(affiliates_path)
expect(flash[:notice]).to eq("Affiliate deleted successfully")
expect(affiliate.reload).to be_deleted
end
it "returns 404 for non-existent affiliate" do
expect { delete :destroy, params: { id: "nonexistent" } }.to raise_error(ActionController::RoutingError)
end
end
describe "GET export" do
let!(:affiliate) { create(:direct_affiliate, seller:) }
it_behaves_like "authentication required for action", :post, :export
it_behaves_like "authorize called for action", :post, :export do
let(:record) { DirectAffiliate }
let(:policy_method) { :index? }
end
context "when export is synchronous" do
it "sends data as CSV file" do
get :export
expect(response.header["Content-Type"]).to include "text/csv"
expect(response.body.to_s).to include(affiliate.affiliate_user.email)
end
end
context "when export is asynchronous" do
before do
stub_const("Exports::AffiliateExportService::SYNCHRONOUS_EXPORT_THRESHOLD", 0)
end
it "queues sidekiq job and redirects back" do
get :export
expect(Exports::AffiliateExportWorker).to have_enqueued_sidekiq_job(seller.id, seller.id)
expect(flash[:warning]).to eq("You will receive an email with the data you've requested.")
expect(response).to redirect_to(affiliates_path)
end
context "when admin is signed in and impersonates seller" do
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
controller.impersonate_user(seller)
end
it "queues sidekiq job for the admin" do
get :export
expect(Exports::AffiliateExportWorker).to have_enqueued_sidekiq_job(seller.id, admin_user.id)
expect(flash[:warning]).to eq("You will receive an email with the data you've requested.")
expect(response).to redirect_to(affiliates_path)
end
end
end
end
end
context "within consumer area" do
describe "GET subscribe_posts" do
before do
@direct_affiliate = create(:direct_affiliate, affiliate_user:, seller:, affiliate_basis_points: 1500)
@direct_affiliate_2 = create(:direct_affiliate, affiliate_user:, seller:,
affiliate_basis_points: 2500, deleted_at: Time.current)
end
it "successfully marks current user's all affiliate records for this creator as subscribed" do
sign_in(affiliate_user)
@direct_affiliate.update!(send_posts: false)
@direct_affiliate_2.update!(send_posts: false)
get :subscribe_posts, params: { id: @direct_affiliate.external_id }
expect(@direct_affiliate.reload.send_posts).to be true
expect(@direct_affiliate_2.reload.send_posts).to be true
end
end
describe "GET unsubscribe_posts" do
before do
@direct_affiliate = create(:direct_affiliate, affiliate_user:, seller:,
affiliate_basis_points: 1500, deleted_at: Time.current)
@direct_affiliate_2 = create(:direct_affiliate, affiliate_user:, seller:,
affiliate_basis_points: 2500)
end
it "successfully marks current user's all affiliate records for this creator as unsubscribed" do
sign_in(affiliate_user)
expect(@direct_affiliate.send_posts).to be true
expect(@direct_affiliate_2.send_posts).to be true
get :unsubscribe_posts, params: { id: @direct_affiliate_2.external_id }
expect(@direct_affiliate.reload.send_posts).to be false
expect(@direct_affiliate_2.reload.send_posts).to be false
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/utm_links_controller_spec.rb | spec/controllers/utm_links_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe UtmLinksController do
let(:seller) { create(:user) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
include_context "with user signed in as admin for seller"
before do
Feature.activate_user(:utm_links, seller)
end
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { UtmLink }
end
it "returns unauthorized response if the :utm_links feature flag is disabled" do
Feature.deactivate_user(:utm_links, seller)
get :index
expect(response).to redirect_to dashboard_path
expect(flash[:alert]).to eq("Your current role as Admin cannot perform this action.")
end
it "renders the page" do
get :index
expect(response).to be_successful
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/analytics_controller_spec.rb | spec/controllers/analytics_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe AnalyticsController do
render_views
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { :analytics }
end
context "stripe connect requirements" do
before do
create(:merchant_account, user: seller)
$redis.sadd(RedisKey.user_ids_with_payment_requirements_key, seller.id)
@stripe_account = double
allow(Stripe::Account).to receive(:retrieve).and_return(@stripe_account)
end
it "does not redirect to payout settings page if user not part of user_ids_with_payment_requirements_key" do
$redis.srem(RedisKey.user_ids_with_payment_requirements_key, seller.id)
get :index
expect(response).to_not redirect_to(settings_payments_path)
end
it "redirects to payout settings page if compliance requests exist" do
create(:user_compliance_info_request, user: seller, state: :requested)
get :index
expect(response).to redirect_to(settings_payments_path)
expect(flash[:notice]).to eq("Urgent: We are required to collect more information from you to continue processing payments.")
end
it "redirects to payout settings page if capabilities missing" do
allow(@stripe_account).to receive(:capabilities).and_return({})
get :index
expect(response).to redirect_to(settings_payments_path)
expect(flash[:notice]).to eq("Urgent: We are required to collect more information from you to continue processing payments.")
end
it "removes from users that need requirements if capabilities are satisfied" do
allow(@stripe_account).to receive(:capabilities).and_return({ card_payments: "active",
legacy_payments: "active",
transfers: "active" })
get :index
expect(response).to_not redirect_to(settings_payments_path)
expect($redis.sismember(RedisKey.user_ids_with_payment_requirements_key, seller.id)).to eq(false)
end
end
describe "when user is not qualified for analytics" do
before :each do
allow(controller.logged_in_user).to receive(:visible).and_return([])
allow(controller.logged_in_user).to receive(:successful_or_preorder_authorization_successful).and_return([])
end
it "assigns props" do
get :index
expect(assigns(:analytics_props)).to_not be(nil)
end
end
describe "when user is qualified for analytics" do
before :each do
allow(controller.logged_in_user).to receive(:visible).and_return([Link.new])
allow(controller.logged_in_user).to receive(:successful_or_preorder_authorization_successful).and_return([Purchase.new])
product = create(:product, user: seller)
create(:purchase, link: product, price_cents: 100, purchase_state: "successful")
end
it "sets the last viewed dashboard cookie" do
get :index
expect(response.cookies["last_viewed_dashboard"]).to eq "sales"
end
it "assigns props" do
get :index
expect(assigns(:analytics_props)).to_not be(nil)
end
it "does not call prepare_demo" do
expect(controller).to_not receive(:prepare_demo)
get :index
end
it "attemps to create related LargeSeller record" do
expect(LargeSeller).to receive(:create_if_warranted).with(controller.current_seller)
get :index
end
end
end
shared_examples "supports start and end times" do |action_name|
it "assigns the correct @start_date and @end_date" do
get(action_name, params: {
start_time: "Tue May 25 2021 14:32:31 GMT 0700 (Novosibirsk Standard Time)",
end_time: "Wed Jun 23 2021 14:32:31 GMT 0700 (Novosibirsk Standard Time)",
})
expect(assigns(:start_date)).to eq(Date.new(2021, 5, 25))
expect(assigns(:end_date)).to eq(Date.new(2021, 6, 23))
end
end
describe "GET data_by_date" do
before do
@stats = { data: "data" }
end
it_behaves_like "supports start and end times", :data_by_date
it_behaves_like "authorize called for action", :get, :data_by_date do
let(:record) { :analytics }
let(:policy_method) { :index? }
end
describe "when start_time and end_time are valid" do
it "gets analytics stats range from start_time to end_time" do
start_time = "Mon Apr 8 2013 22:40:18 GMT-0700 (PDT)"
end_time = "Wed Apr 10 2013 22:40:18 GMT-0700 (PDT)"
expected_start_time = Date.parse(start_time)
expected_end_time = Date.parse(end_time)
expect_any_instance_of(CreatorAnalytics::CachingProxy).to receive(:data_for_dates).with(expected_start_time, expected_end_time, by: :date).and_return(@stats)
get :data_by_date, params: { start_time:, end_time: }
expect(response.body).to eq(@stats.to_json)
end
it "renders stats in json format" do
get :data_by_date
end
end
describe "when start_time or end_time is invalid" do
it "gets analytics stats range from 29 days ago to today" do
now = DateTime.current
allow(Date).to receive(:now).and_return(now)
expected_start_time = now.to_date.ago(29.days)
expected_end_time = now.to_date
expect_any_instance_of(CreatorAnalytics::CachingProxy).to receive(:data_for_dates).with(expected_start_time, expected_end_time, by: :date).and_return(@stats)
get :data_by_date
expect(response.body).to eq(@stats.to_json)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/acme_challenges_controller_spec.rb | spec/controllers/acme_challenges_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AcmeChallengesController do
describe "GET 'show'" do
let(:token) { "a" * 43 }
let(:challenge_content) { "challenge-response-content" }
context "when challenge exists in Redis" do
before do
$redis.set(RedisKey.acme_challenge(token), challenge_content)
end
after do
$redis.del(RedisKey.acme_challenge(token))
end
it "returns the challenge content" do
get :show, params: { token: token }
expect(response.status).to eq(200)
expect(response.body).to eq(challenge_content)
end
end
context "when challenge does not exist in Redis" do
it "returns not found" do
get :show, params: { token: token }
expect(response.status).to eq(404)
end
end
context "when token is too long" do
it "returns bad request" do
get :show, params: { token: "a" * 65 }
expect(response.status).to eq(400)
end
end
context "when token contains invalid characters" do
it "returns bad request" do
get :show, params: { token: "invalid!token@chars" }
expect(response.status).to eq(400)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/asset_previews_controller_spec.rb | spec/controllers/asset_previews_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe AssetPreviewsController do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:s3_url) { "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}/specs/test.png" }
include_context "with user signed in as admin for seller"
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:record) { AssetPreview }
let(:request_params) { { link_id: product.unique_permalink, asset_preview: { url: s3_url }, format: :json } }
end
it "fails if not logged in" do
sign_out(user_with_role_for_seller)
expect do
expect do
post(:create, params: { link_id: product.id, asset_preview: { url: s3_url } })
end.to raise_error(ActionController::RoutingError, "Not Found")
end.to_not change { AssetPreview.count }
end
it "adds a preview if one already exists" do
allow_any_instance_of(AssetPreview).to receive(:analyze_file).and_return(nil)
product = create(:product, user: seller, preview: fixture_file_upload("kFDzu.png", "image/png"))
expect do
post(:create, params: { link_id: product.unique_permalink, asset_preview: { url: s3_url }, format: :json })
end.to change { product.asset_previews.alive.count }.by(1)
end
it "doesn't add a preview if there are too many previews" do
stub_const("Link::MAX_PREVIEW_COUNT", 1)
allow_any_instance_of(AssetPreview).to receive(:analyze_file).and_return(nil)
allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil)
create(:asset_preview, link: product)
expect do
post(:create, params: { link_id: product.unique_permalink, asset_preview: { url: s3_url }, format: :json })
end.to_not change { AssetPreview.count }
end
end
describe "DELETE destroy" do
let!(:asset_preview) { create(:asset_preview, link: product) }
it_behaves_like "authorize called for action", :post, :destroy do
let(:record) { asset_preview }
let(:request_params) { { link_id: product.unique_permalink, id: product.main_preview.guid } }
end
it "fails if not logged in" do
sign_out(user_with_role_for_seller)
expect do
expect do
delete(:destroy, params: { link_id: product.unique_permalink, id: product.main_preview.guid })
end.to raise_error(ActionController::RoutingError, "Not Found")
end.to_not change { product.asset_previews.alive.count }
end
it "removes a preview" do
expect do
delete(:destroy, params: { link_id: product.unique_permalink, id: product.main_preview.guid })
end.to change { product.asset_previews.alive.count }.from(1).to(0)
expect(product.main_preview).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/controllers/paypal_controller_spec.rb | spec/controllers/paypal_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe PaypalController, :vcr do
include AffiliateCookie
let(:window_location) { "https://127.0.0.1:3000/l/test?wanted=true" }
let(:paypal_auth_token) { "Bearer A21AAF5T7EesDXLWLuLRvWyMYLvqXkVxpL_exqSEColXRRl47BxzjIKhdWgw-rD2NT_hXvDyKa1bz9FBNCP24WDrd33dtD0kg" }
before do
allow_any_instance_of(PaypalPartnerRestCredentials).to receive(:auth_token).and_return(paypal_auth_token)
end
describe "#billing_agreement_token" do
before { allow_any_instance_of(PaypalRestApi).to receive(:timestamp).and_return("1572552322") }
context "when request passes" do
it "returns a valid billing agreement token id" do
post :billing_agreement_token, params: { window_location: }
expect(response.parsed_body["billing_agreement_token_id"]).to be_a(String)
expect(response.parsed_body["billing_agreement_token_id"]).to_not be(nil)
end
end
end
describe "#billing_agreement" do
context "when request is invalid" do
it "returns nil" do
post :billing_agreement, params: { billing_agreement_token_id: "invalid_billing_agreement_token_id" }
expect(response.body).to eq("null")
end
end
context "when request is valid" do
let(:valid_billing_agreement_token_id) { "BA-7TR16712TA5219609" }
it "returns a valid billing agreement" do
post :billing_agreement, params: { billing_agreement_token_id: valid_billing_agreement_token_id }
expect(response.parsed_body["id"]).to_not be(nil)
expect(response.parsed_body["id"]).to be_a(String)
end
end
end
describe "#connect" do
let(:partner_referral_success_response) do
{
success: true,
redirect_url: "http://dummy-paypal-url.com"
}
end
let(:partner_referral_failure_response) do
{
success: false,
error_message: "Invalid request. Please try again later."
}
end
before do
@user = create(:user)
create(:user_compliance_info, user: @user)
sign_in(@user)
@user.mark_compliant!(author_name: "Iffy")
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(100_00)
create(:payment_completed, user: @user)
allow_any_instance_of(PaypalMerchantAccountManager)
.to receive(:create_partner_referral).and_return(partner_referral_success_response)
end
it_behaves_like "authorize called for action", :get, :connect do
let(:record) { @user }
let(:policy_klass) { Settings::Payments::UserPolicy }
let(:policy_method) { :paypal_connect? }
end
context "when logged in user is admin of seller account" do
let(:admin) { create(:user) }
before do
create(:team_membership, user: admin, seller: @user, role: TeamMembership::ROLE_ADMIN)
cookies.encrypted[:current_seller_id] = @user.id
sign_in admin
end
it_behaves_like "authorize called for action", :get, :connect do
let(:record) { @user }
let(:policy_klass) { Settings::Payments::UserPolicy }
let(:policy_method) { :paypal_connect? }
end
end
it "creates paypal partner-referral for the current user" do
expect_any_instance_of(PaypalMerchantAccountManager).to receive(:create_partner_referral).and_return(partner_referral_success_response)
get :connect
end
it "returns an error alert if user is from a country where PayPal Connect is not supported" do
create(:user_compliance_info, user: @user, country: "Egypt")
get :connect
expect(response).to redirect_to(settings_payments_path)
expect(flash[:alert]).to eq("Your PayPal account could not be connected because this PayPal integration is not supported in your country.")
end
it "returns an error alert if user is not allowed to connect their PayPal account" do
@user.update!(user_risk_state: "not_reviewed")
get :connect
expect(response).to redirect_to(settings_payments_path)
expect(flash[:alert]).to eq("Your PayPal account could not be connected because you do not meet the eligibility requirements.")
end
context "when response is success" do
it "redirects to the paypal url" do
get :connect
expect(response).to redirect_to(partner_referral_success_response[:redirect_url])
end
end
context "when response is failure" do
before do
allow_any_instance_of(PaypalMerchantAccountManager)
.to receive(:create_partner_referral).and_return(partner_referral_failure_response)
get :connect
end
it "redirects to the payment settings path" do
expect(response).to redirect_to(settings_payments_path)
end
it "show error in flash" do
expect(flash[:notice]).to eq("Invalid request. Please try again later.")
end
end
end
describe "#disconnect" do
before do
@user = create(:user)
sign_in(@user)
@merchant_account = create(:merchant_account, user: @user,
charge_processor_merchant_id: "PaypalAccountID",
charge_processor_id: "paypal",
charge_processor_verified_at: Time.current,
charge_processor_alive_at: Time.current)
end
it_behaves_like "authorize called for action", :post, :disconnect do
let(:record) { @user }
let(:policy_klass) { Settings::Payments::UserPolicy }
let(:policy_method) { :paypal_connect? }
end
context "when logged in user is admin of seller account" do
let(:admin) { create(:user) }
before do
create(:team_membership, user: admin, seller: @user, role: TeamMembership::ROLE_ADMIN)
cookies.encrypted[:current_seller_id] = @user.id
sign_in admin
end
it_behaves_like "authorize called for action", :post, :disconnect do
let(:record) { @user }
let(:policy_klass) { Settings::Payments::UserPolicy }
let(:policy_method) { :paypal_connect? }
end
end
it "redirects if logged_in_user is not present" do
sign_out(@user)
post :disconnect
expect(response).to redirect_to(login_url(next: request.path))
end
it "marks the paypal merchant account as deleted but does not clear the charge processor merchant id" do
expect(@user.merchant_account(PaypalChargeProcessor.charge_processor_id).charge_processor_merchant_id).to eq("PaypalAccountID")
post :disconnect
expect(@user.merchant_account(PaypalChargeProcessor.charge_processor_id)).to be(nil)
expect(@merchant_account.reload.charge_processor_merchant_id).to eq("PaypalAccountID")
end
it "allows disconnecting a paypal merchant account that is not charge_processor_alive" do
@merchant_account.charge_processor_alive_at = nil
@merchant_account.save!
expect(@user.merchant_account(PaypalChargeProcessor.charge_processor_id)).to be(nil)
expect(@user.merchant_accounts.alive.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id).last.charge_processor_merchant_id).to eq("PaypalAccountID")
post :disconnect
expect(@user.merchant_account(PaypalChargeProcessor.charge_processor_id)).to be(nil)
expect(@user.merchant_accounts.alive.where(charge_processor_id: PaypalChargeProcessor.charge_processor_id).count).to eq(0)
expect(@merchant_account.reload.charge_processor_merchant_id).to eq("PaypalAccountID")
end
it "does nothing and redirects to payments settings page if paypal disconnect is not allowed" do
allow_any_instance_of(User).to receive(:paypal_disconnect_allowed?).and_return(false)
post :disconnect
expect(@user.merchant_account(PaypalChargeProcessor.charge_processor_id).charge_processor_merchant_id).to eq("PaypalAccountID")
expect(response).to redirect_to(settings_payments_url)
expect(flash[:notice]).to eq("You cannot disconnect your PayPal account because it is being used for active subscription or preorder payments.")
end
end
describe "#order" do
before { allow_any_instance_of(PaypalRestApi).to receive(:timestamp).and_return("1572552322") }
let(:product) { create(:product, :recommendable) }
let(:product_info) do
{
external_id: product.external_id,
currency_code: "usd",
price_cents: "1500",
shipping_cents: "150",
tax_cents: "100",
exclusive_tax_cents: "100",
total_cents: "1750",
quantity: 3
}
end
let!(:merchant_account) { create(:merchant_account_paypal, user: product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L") }
before do
expect(PaypalChargeProcessor).to receive(:create_order_from_product_info).and_call_original
end
it "creates new paypal order" do
post :order, params: { product: product_info }
expect(response.parsed_body["order_id"]).to be_present
end
context "for affiliate sales" do
let(:purchase_info) do
{
amount_cents: product_info[:price_cents].to_i,
vat_cents: 0,
affiliate_id: nil,
was_recommended: false,
}
end
context "by a direct affiliate" do
let(:affiliate) { create(:direct_affiliate, seller: product.user, products: [product]) }
before do
create_affiliate_id_cookie(affiliate)
end
it "credits the affiliate" do
expect_any_instance_of(Link).to receive(:gumroad_amount_for_paypal_order).with(purchase_info.merge(affiliate_id: affiliate.id))
post :order, params: { product: product_info }
end
it "does not credit the affiliate for a Discover purchase" do
expect_any_instance_of(Link).to receive(:gumroad_amount_for_paypal_order).with(purchase_info.merge(was_recommended: true))
post :order, params: { product: product_info.merge(was_recommended: "true") }
end
end
context "by a global affiliate" do
let(:affiliate) { create(:user).global_affiliate }
before do
create_affiliate_id_cookie(affiliate)
end
it "credits the affiliate" do
expect_any_instance_of(Link).to receive(:gumroad_amount_for_paypal_order).with(purchase_info.merge(affiliate_id: affiliate.id))
post :order, params: { product: product_info }
end
it "credits the affiliate even for a Discover purchase" do
expect_any_instance_of(Link).to receive(:gumroad_amount_for_paypal_order).with(purchase_info.merge(affiliate_id: affiliate.id, was_recommended: true))
post :order, params: { product: product_info.merge(was_recommended: "true") }
end
end
end
end
describe "#fetch_order" do
context "when request is invalid" do
it "returns nil" do
get :fetch_order, params: { order_id: "invalid_order" }
expect(response.body).to eq({}.to_json)
end
end
context "when request is valid" do
it "returns the paypal order details" do
get :fetch_order, params: { order_id: "9J862133JL8076730" }
order_id = response.parsed_body["id"]
expect(order_id).to eq("9J862133JL8076730")
end
end
end
describe "update_order" do
before { allow_any_instance_of(PaypalRestApi).to receive(:timestamp).and_return("1572552322") }
let(:product) { create(:product, :recommendable) }
let(:product_info) do
{
external_id: product.external_id,
currency_code: "usd",
price_cents: "1500",
shipping_cents: "150",
tax_cents: "100",
exclusive_tax_cents: "100",
total_cents: "1750",
quantity: 3
}
end
let(:updated_product_info) do
{
external_id: product.external_id,
currency_code: "usd",
price_cents: "750",
shipping_cents: "75",
tax_cents: "50",
exclusive_tax_cents: "50",
total_cents: "875",
quantity: 3
}
end
let!(:merchant_account) { create(:merchant_account_paypal, user: product.user, charge_processor_merchant_id: "CJS32DZ7NDN5L") }
before do
expect(PaypalChargeProcessor).to receive(:update_order_from_product_info).and_call_original
end
it "updates the paypal order with the given info and returns true" do
paypal_order_id = PaypalChargeProcessor.create_order_from_product_info(product_info)
post :update_order, params: { order_id: paypal_order_id, product: updated_product_info }
expect(response.parsed_body["success"]).to be(true)
end
it "returns false if updating the paypal order with the given info fails" do
expect(PaypalChargeProcessor).to receive(:update_order).and_raise(ChargeProcessorError)
paypal_order_id = PaypalChargeProcessor.create_order_from_product_info(product_info)
post :update_order, params: { order_id: paypal_order_id, product: updated_product_info }
expect(response.parsed_body["success"]).to be(false)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.