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/controllers/foreign_webhooks_controller_spec.rb | spec/controllers/foreign_webhooks_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
describe ForeignWebhooksController do
before do
@query = { some: "data", and: { nested: "data" } }
end
describe "#stripe" do
it "responds successfully to charge.succeeded" do
json = { type: "charge.succeeded", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "1" }
endpoint_secret = GlobalConfig.dig(:stripe, :endpoint_secret)
request.headers["Stripe-Signature"] = stripe_signature_header(json, endpoint_secret)
post :stripe, params: json, as: :json
expect(response).to be_successful
expect(HandleStripeEventWorker).to have_enqueued_sidekiq_job(json)
end
it "responds successfully to charge.refunded" do
json = { type: "charge.refunded", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "1" }
endpoint_secret = GlobalConfig.dig(:stripe, :endpoint_secret)
request.headers["Stripe-Signature"] = stripe_signature_header(json, endpoint_secret)
post :stripe, params: json, as: :json
expect(response).to be_successful
expect(HandleStripeEventWorker).to have_enqueued_sidekiq_job(json)
end
it "responds with bad request for invalid stripe signature" do
json = { type: "charge.succeeded", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "1" }
request.headers["Stripe-Signature"] = "invalid"
post :stripe, params: json
expect(response).to be_a_bad_request
expect(HandleStripeEventWorker.jobs.size).to eq(0)
end
it "responds with bad request for missing stripe signature header" do
json = { type: "charge.succeeded", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "1" }
post :stripe, params: json
expect(response).to be_a_bad_request
expect(HandleStripeEventWorker.jobs.size).to eq(0)
end
end
describe "#stripe_connect" do
it "responds successfully" do
json = { type: "transfer.paid", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "acct_1234" }
endpoint_secret = GlobalConfig.dig(:stripe_connect, :endpoint_secret)
request.headers["Stripe-Signature"] = stripe_signature_header(json, endpoint_secret)
post :stripe_connect, params: json, as: :json
expect(response).to be_successful
expect(HandleStripeEventWorker).to have_enqueued_sidekiq_job(json)
end
it "responds with bad request for invalid stripe signature" do
json = { type: "transfer.paid", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "acct_1234" }
request.headers["Stripe-Signature"] = "invalid"
post :stripe_connect, params: json, as: :json
expect(response).to be_a_bad_request
expect(HandleStripeEventWorker.jobs.size).to eq(0)
end
it "responds with bad request for missing stripe signature header" do
json = { type: "transfer.paid", id: "evt_dafasdfadsf", pending_webhooks: "0", user_id: "acct_1234" }
post :stripe_connect, params: json, as: :json
expect(response).to be_a_bad_request
expect(HandleStripeEventWorker.jobs.size).to eq(0)
end
end
describe "#paypal" do
it "responds successfully" do
expect(PaypalEventHandler).to receive(:new).with(@query.as_json).and_call_original
expect_any_instance_of(PaypalEventHandler).to receive(:schedule_paypal_event_processing)
post :paypal, params: @query
expect(response).to be_successful
end
# The test ensures we're converting the request params to be Sidekiq-compliant which is a little hard to assert in
# the spec above.
it "enqueues a HandlePaypalEventWorker job with the correct arguments" do
post :paypal, params: @query
expect(response).to be_successful
expect(HandlePaypalEventWorker).to have_enqueued_sidekiq_job(@query)
end
end
describe "#sendgrid" do
it "responds successfully" do
post :sendgrid, params: @query
expect(HandleSendgridEventJob).to have_enqueued_sidekiq_job(@query.merge(controller: "foreign_webhooks", action: "sendgrid"))
expect(LogSendgridEventWorker).to have_enqueued_sidekiq_job(@query.merge(controller: "foreign_webhooks", action: "sendgrid"))
expect(response).to be_successful
end
end
describe "#resend" do
let(:timestamp) { Time.current.to_i }
let(:message_id) { "msg_123" }
let(:payload) { { some: "data", and: { nested: "data" } } }
let(:secret) { "whsec_test123" }
let(:secret_bytes) { Base64.decode64(secret.split("_", 2).last) }
before do
allow(GlobalConfig).to receive(:get).with("RESEND_WEBHOOK_SECRET").and_return(secret)
@json = payload.to_json
signed_payload = "#{message_id}.#{timestamp}.#{@json}"
signature = Base64.strict_encode64(OpenSSL::HMAC.digest("SHA256", secret_bytes, signed_payload))
request.headers["svix-signature"] = "v1,#{signature}"
request.headers["svix-timestamp"] = timestamp.to_s
request.headers["svix-id"] = message_id
end
context "with valid signature" do
it "responds successfully" do
post :resend, params: payload, as: :json
expected_params = payload.merge(
format: "json",
controller: "foreign_webhooks",
action: "resend",
foreign_webhook: payload
)
expect(HandleResendEventJob).to have_enqueued_sidekiq_job(expected_params)
expect(LogResendEventJob).to have_enqueued_sidekiq_job(expected_params)
expect(response).to be_successful
end
end
context "with missing headers" do
it "returns bad request when signature is missing" do
request.headers["svix-signature"] = nil
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Missing signature")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
it "returns bad request when timestamp is missing" do
request.headers["svix-timestamp"] = nil
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Missing timestamp")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
it "returns bad request when message ID is missing" do
request.headers["svix-id"] = nil
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Missing message ID")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
end
context "with invalid signature" do
it "returns bad request when signature format is invalid" do
request.headers["svix-signature"] = "invalid"
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Invalid signature format")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
it "returns bad request when signature is incorrect" do
request.headers["svix-signature"] = "v1,invalid"
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Invalid signature")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
end
context "with old timestamp" do
it "returns bad request when timestamp is too old" do
request.headers["svix-timestamp"] = (6.minutes.ago.to_i).to_s
expect(Bugsnag).to receive(:notify).with("Error verifying Resend webhook: Timestamp too old")
post :resend, params: payload, as: :json
expect(response).to be_a_bad_request
expect(HandleResendEventJob.jobs.size).to eq(0)
expect(LogResendEventJob.jobs.size).to eq(0)
end
end
end
describe "POST sns" do
it "enqueues a HandleSnsTranscoderEventWorker job with correct params" do
notification = { abc: "123" }
post :sns, body: notification.to_json, as: :json
expect(HandleSnsTranscoderEventWorker).to have_enqueued_sidekiq_job(notification)
end
context "body contains invalid chars" do
controller(ForeignWebhooksController) do
skip_before_action :set_signup_referrer
end
before do
routes.draw { post "sns" => "foreign_webhooks#sns" }
end
it "enqueues a HandleSnsTranscoderEventWorker job after removing invalid chars" do
post :sns, body: '{ "abc"#012: "xyz" }', as: :json
expect(HandleSnsTranscoderEventWorker).to have_enqueued_sidekiq_job({ abc: "xyz" })
end
end
end
describe "POST mediaconvert" do
let(:notification) do
{
"Type" => "Notification",
"Message" => {
"detail" => {
"jobId" => "abcd",
"status" => "COMPLETE",
"outputGroupDetails" => [
"playlistFilePaths" => [
"s3://#{S3_BUCKET}/path/to/playlist/file.m3u8"
]
]
}
}.to_json
}
end
context "when SNS notification is valid" do
before do
allow_any_instance_of(Aws::SNS::MessageVerifier).to receive(:authentic?).and_return(true)
end
it "enqueues a HandleSnsMediaconvertEventWorker job with notification" do
post :mediaconvert, body: notification.to_json, as: :json
expect(HandleSnsMediaconvertEventWorker).to have_enqueued_sidekiq_job(notification)
end
end
context "when SNS notification is invalid" do
before do
allow_any_instance_of(Aws::SNS::MessageVerifier).to receive(:authentic?).and_return(false)
end
it "renders bad request response" do
post :mediaconvert, body: notification.to_json, as: :json
expect(response).to be_a_bad_request
expect(HandleSnsMediaconvertEventWorker.jobs.size).to eq(0)
end
end
end
private
def stripe_signature_header(payload, secret)
timestamp = Time.now.utc
signature = Stripe::Webhook::Signature.compute_signature(timestamp, payload.to_json, secret)
Stripe::Webhook::Signature.generate_header(timestamp, signature)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/connections_controller_spec.rb | spec/controllers/connections_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe ConnectionsController do
let(:seller) { create(:named_seller) }
before :each do
sign_in seller
end
it_behaves_like "authorize called for controller", Settings::ProfilePolicy do
let(:record) { :profile }
let(:policy_method) { :manage_social_connections? }
end
describe "POST unlink_twitter" do
before do
seller.twitter_user_id = "123"
seller.twitter_handle = "gumroad"
seller.save!
end
it "unsets all twitter properties" do
post :unlink_twitter
seller.reload
User::SocialTwitter::TWITTER_PROPERTIES.each do |property|
expect(seller.attributes[property]).to be(nil)
end
expect(response.body).to eq({ success: true }.to_json)
end
it "responds with an error message if the unlink fails" do
allow_any_instance_of(User).to receive(:save!).and_raise("Failed to unlink Twitter")
post :unlink_twitter
expect(response.body).to eq({ success: false, error_message: "Failed to unlink Twitter" }.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/logins_controller_spec.rb | spec/controllers/logins_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/merge_guest_cart_with_user_cart"
require "inertia_rails/rspec"
describe LoginsController, type: :controller, inertia: true do
render_views
before :each do
request.env["devise.mapping"] = Devise.mappings[:user]
end
describe "GET 'new'" do
it "renders successfully" do
get :new
expect(response).to be_successful
expect(inertia.component).to eq("Logins/New")
expect(inertia.props[:current_user]).to be_nil
expect(inertia.props[:title]).to eq("Log In")
expect(inertia.props[:email]).to be_nil
expect(inertia.props[:application_name]).to be_nil
expect(inertia.props[:recaptcha_site_key]).to eq(GlobalConfig.get("RECAPTCHA_LOGIN_SITE_KEY"))
end
context "with an email in the query parameters" do
it "renders successfully" do
get :new, params: { email: "test@example.com" }
expect(response).to be_successful
expect(inertia.component).to eq("Logins/New")
expect(inertia.props[:email]).to eq("test@example.com")
end
end
context "with an email in the next parameter" do
it "renders successfully" do
get :new, params: { next: settings_team_invitations_path(email: "test@example.com", format: :json) }
expect(response).to be_successful
expect(inertia.component).to eq("Logins/New")
expect(inertia.props[:email]).to eq("test@example.com")
end
end
it "redirects with the 'next' value from the referrer if not supplied in the params" do
@request.env["HTTP_REFERER"] = products_path
get :new
expect(response).to redirect_to(login_path(next: products_path))
end
it "does not redirect with the 'next' value from the referrer if it equals to the root route" do
@request.env["HTTP_REFERER"] = root_path
get :new
expect(response).to be_successful
end
describe "OAuth login" 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 "renders successfully" do
get :new, params: { next: @next_url }
expect(response).to be_successful
expect(inertia.component).to eq("Logins/New")
expect(inertia.props[:application_name]).to eq(@oauth_application.name)
end
it "responds with bad request if format is json" do
get :new, params: { next: @next_url }, format: :json
expect(response).to be_a_bad_request
end
it "sets the application" do
get :new, params: { next: @next_url }
expect(assigns[:application]).to eq @oauth_application
end
it "sets noindex header when next param starts with /oauth/authorize" do
get :new, params: { next: "/oauth/authorize?client_id=123" }
expect(response.headers["X-Robots-Tag"]).to eq "noindex"
end
it "does not set noindex header for regular login" do
get :new
expect(response.headers["X-Robots-Tag"]).to be_nil
end
end
end
describe "POST create" do
before do
@user = create(:user, password: "password")
end
it "logs in if user already exists" do
post "create", params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
end
it "shows proper error if password is incorrect" do
post "create", params: { user: { login_identifier: @user.email, password: "hunter2" } }
expect(response).to redirect_to(login_path)
expect(flash[:warning]).to eq("Please try another password. The one you entered was incorrect.")
end
it "shows proper error if email doesn't exist" do
post "create", params: { user: { login_identifier: "hithere@gumroaddddd.com", password: "password" } }
expect(response).to redirect_to(login_path)
expect(flash[:warning]).to eq("An account does not exist with that email.")
end
it "returns an error with no params" do
post "create"
expect(response).to redirect_to(login_path)
expect(flash[:warning]).to eq("An account does not exist with that email.")
end
it "logs in if user already exists and redirects to next if present" do
post "create", params: { user: { login_identifier: @user.email, password: "password" }, next: "/about" }
expect(response).to redirect_to("/about")
end
it "does not redirect to absolute url" do
post "create", params: { user: { login_identifier: @user.email, password: "password" }, next: "https://elite.haxor.net/home?steal=everything#yes" }
expect(response).to redirect_to("/home?steal=everything")
end
it "redirects back to subdomain URL" do
stub_const("ROOT_DOMAIN", "test.gumroad.com")
post "create", params: { user: { login_identifier: @user.email, password: "password" }, next: "https://username.test.gumroad.com" }
expect(response).to redirect_to("https://username.test.gumroad.com")
end
it "disallows logging in if the user has been deleted" do
@user.deleted_at = Time.current
@user.save!
post "create", params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(login_path)
expect(flash[:warning]).to eq("You cannot log in because your account was permanently deleted. Please sign up for a new account to start selling!")
end
it "does not log in a user when reCAPTCHA is not completed" do
allow(controller).to receive(:valid_recaptcha_response?).and_return(false)
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(login_path)
expect(flash[:warning]).to eq "Sorry, we could not verify the CAPTCHA. Please try again."
expect(controller.user_signed_in?).to be(false)
end
it "logs in a user when reCAPTCHA is completed correctly" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
expect(controller.user_signed_in?).to be(true)
end
it "logs in a user when reCAPTCHA site key is not set in development environment" do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("development"))
allow(GlobalConfig).to receive(:get).with("RECAPTCHA_LOGIN_SITE_KEY").and_return(nil)
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
expect(controller.user_signed_in?).to be(true)
end
it "does not log in a user when reCAPTCHA site key is not set in production environment" do
allow(Rails).to receive(:env).and_return(ActiveSupport::StringInquirer.new("production"))
allow(GlobalConfig).to receive(:get).with("RECAPTCHA_LOGIN_SITE_KEY").and_return(nil)
allow_any_instance_of(LoginsController).to receive(:valid_recaptcha_response?).and_return(false)
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(login_path)
expect(controller.user_signed_in?).to be(false)
end
it "sets the 'Remember Me' cookie" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response.cookies["remember_user_token"]).to be_present
end
describe "user suspended" do
before do
@bad_user = create(:user)
end
describe "for ToS violation" do
before do
@product = create(:product, user: @user)
@user.flag_for_tos_violation(author_id: @bad_user.id, product_id: @product.id)
@user.suspend_for_tos_violation(author_id: @bad_user.id)
end
it "is allowed to login" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
end
end
it "does not log in a user who is suspended for fraud" do
user = create(:user, password: "password", user_risk_state: "suspended_for_fraud")
post :create, params: { user: { login_identifier: user.email, password: "password" } }
expect(flash[:warning]).to eq("You can't perform this action because your account has been suspended.")
expect(controller.user_signed_in?).to be(false)
end
end
describe "referrer present" do
describe "referrer is root" do
before do
@request.env["HTTP_REFERER"] = root_path
end
describe "buyer" do
before do
@user = create(:user, password: "password")
@purchase = create(:purchase, purchaser: @user)
end
it "redirects to library" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(library_path)
end
end
describe "seller" do
before do
@user = create(:user, password: "password")
end
it "redirects to dashboard" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(dashboard_path)
end
end
end
describe "referrer is not root" do
before do
@product = create(:product)
@request.env["HTTP_REFERER"] = short_link_path(@product)
end
it "redirects back to the last location" do
post :create, params: { user: { login_identifier: @user.email, password: "password" } }
expect(response).to redirect_to(short_link_path(@product))
end
end
end
describe "OAuth login" 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 "redirects to the OAuth authorization path after successful login" do
post "create", params: { user: { login_identifier: @user.email, password: "password" }, next: @next_url }
expect(response).to redirect_to(CGI.unescape(@next_url))
end
end
describe "two factor authentication" 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: { login_identifier: @user.email, password: "password" }, next: settings_main_path }
expect(session[:verify_two_factor_auth_for]).to eq @user.id
expect(response).to redirect_to(two_factor_authentication_path(next: settings_main_path))
expect(controller.user_signed_in?).to eq false
end
end
it_behaves_like "merge guest cart with user cart" do
let(:user) { @user }
let(:call_action) { post "create", params: { user: { login_identifier: user.email, password: "password" } } }
let(:expected_redirect_location) { dashboard_path }
end
end
describe "GET destroy" do
let(:user) { create(:user) }
before do
sign_in user
end
it "clears cookies on sign out" do
cookies["last_viewed_dashboard"] = "sales"
get :destroy
# Ensure that the server instructs the client to clear the cookie
expect(response.cookies.key?("last_viewed_dashboard")).to eq(true)
expect(response.cookies["last_viewed_dashboard"]).to be_nil
end
context "when impersonating" do
let(:admin) { create(:admin_user) }
before do
sign_in admin
controller.impersonate_user(user)
end
it "resets impersonated user" do
expect(controller.impersonated_user).to eq(user)
get :destroy
expect(controller.impersonated_user).to be_nil
expect($redis.get(RedisKey.impersonated_user(admin.id))).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/support_controller_spec.rb | spec/controllers/support_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "inertia_rails/rspec"
describe SupportController, inertia: true do
let(:seller) { create(:named_seller) }
describe "GET index" do
context "when user is signed in" do
before { sign_in seller }
it "returns http success and renders Inertia component with props" do
allow(controller).to receive(:helper_widget_host).and_return("https://help.example.test")
allow(controller).to receive(:helper_session).and_return({ "session_id" => "abc123" })
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Support/Index")
expect(inertia.props[:host]).to eq("https://help.example.test")
expect(inertia.props[:session]).to eq({ session_id: "abc123" })
end
end
context "when user is not signed in" do
it "redirects to help center" do
get :index
expect(response).to redirect_to(help_center_root_path)
end
end
end
describe "POST create_unauthenticated_ticket" do
let(:valid_params) do
{
email: "test@example.com",
subject: "Test subject",
message: "Test message",
"g-recaptcha-response" => "valid_recaptcha_token"
}
end
before do
allow(GlobalConfig).to receive(:get).with("RECAPTCHA_LOGIN_SITE_KEY").and_return("test_recaptcha_key")
allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_HOST").and_return("https://helper.test")
allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_SECRET").and_return("test_secret")
allow(controller).to receive(:valid_recaptcha_response?).and_return(true)
end
context "with valid parameters and successful Helper API" do
before do
stub_request(:post, "https://helper.test/api/widget/session")
.to_return(
status: 200,
body: { token: "mock_helper_token" }.to_json,
headers: { "Content-Type" => "application/json" }
)
stub_request(:post, "https://helper.test/api/chat/conversation")
.to_return(
status: 200,
body: { conversationSlug: "test-conversation-123" }.to_json,
headers: { "Content-Type" => "application/json" }
)
stub_request(:post, "https://helper.test/api/chat/conversation/test-conversation-123/message")
.to_return(
status: 200,
body: { success: true }.to_json,
headers: { "Content-Type" => "application/json" }
)
end
it "creates a support ticket and returns success" do
post :create_unauthenticated_ticket, params: valid_params
expect(response).to have_http_status(:success)
expect(response.parsed_body).to eq({
"success" => true,
"conversation_slug" => "test-conversation-123"
})
expect(WebMock).to have_requested(:post, "https://helper.test/api/widget/session")
.with(body: ->(body) {
expect(JSON.parse(body)).to include(
"email" => "test@example.com",
"emailHash" => kind_of(String),
"timestamp" => kind_of(Integer)
)
})
expect(WebMock).to have_requested(:post, "https://helper.test/api/chat/conversation")
.with(
headers: { "Authorization" => "Bearer mock_helper_token" },
body: ->(body) {
expect(JSON.parse(body)).to include("subject" => "Test subject")
}
)
expect(WebMock).to have_requested(:post, "https://helper.test/api/chat/conversation/test-conversation-123/message")
.with(
headers: { "Authorization" => "Bearer mock_helper_token" },
body: ->(body) {
expect(JSON.parse(body)).to include(
"content" => "Test message",
"customerInfoUrl" => end_with("/internal/helper/users/user_info")
)
}
)
end
end
context "with missing parameters" do
it "returns bad request when email is missing" do
params = valid_params.except(:email)
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: email"
})
end
it "returns bad request when subject is missing" do
params = valid_params.except(:subject)
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: subject"
})
end
it "returns bad request when message is missing" do
params = valid_params.except(:message)
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: message"
})
end
it "returns bad request when email is blank" do
params = valid_params.merge(email: "")
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: email"
})
end
it "returns bad request when subject is blank" do
params = valid_params.merge(subject: "")
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: subject"
})
end
it "returns bad request when message is blank" do
params = valid_params.merge(message: "")
post :create_unauthenticated_ticket, params: params
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body).to eq({
"error" => "Missing required parameters: message"
})
end
end
context "with invalid reCAPTCHA" do
before do
allow(controller).to receive(:valid_recaptcha_response?).and_return(false)
end
it "returns unprocessable entity when recaptcha verification fails" do
post :create_unauthenticated_ticket, params: valid_params
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body).to eq({
"error" => "reCAPTCHA verification failed"
})
end
it "calls recaptcha validation with correct site key" do
expect(controller).to receive(:valid_recaptcha_response?).with(
site_key: "test_recaptcha_key"
).and_return(false)
post :create_unauthenticated_ticket, params: valid_params
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_link_tracking_controller_spec.rb | spec/controllers/utm_link_tracking_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UtmLinkTrackingController do
let(:utm_link) { create(:utm_link) }
before do
Feature.activate_user(:utm_links, utm_link.seller)
end
describe "GET show" do
it "raises error if the :utm_links feature flag is disabled" do
Feature.deactivate_user(:utm_links, utm_link.seller)
expect do
get :show, params: { permalink: utm_link.permalink }
end.to raise_error(ActionController::RoutingError)
end
it "redirects to the utm_link's url" do
get :show, params: { permalink: utm_link.permalink }
expect(response).to redirect_to(utm_link.utm_url)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/s3_utility_controller_spec.rb | spec/controllers/s3_utility_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe S3UtilityController do
include CdnUrlHelper
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", S3UtilityPolicy do
let(:record) { :s3_utility }
end
describe "GET generate_multipart_signature" do
it "doesn't allow sellers to sign request for buckets they do not own" do
sign_string = "POST\n\nvideo/quicktime; charset=UTF-8\n\nx-amz-acl:private\nx-amz-date:Mon, 02 Mar 2015 17:21:19 \
GMT\n/gumroad-specs/attachments/#{seller.external_id + 'invalid'}/bf03be06616f4dfd88da7c37005a9b2f/original/capturedvideo%20(1)-5-2.mov?uploads"
get :generate_multipart_signature, params: { to_sign: sign_string }
expect(response.parsed_body["success"]).to be(false)
expect(response).to be_forbidden
end
it "doesn't allow if an attacker splits the request with newlines" do
sign_string = "GET /?response-content-type=\n/gumroad-specs/attachments/#{seller.external_id}/test"
get :generate_multipart_signature, params: { to_sign: sign_string }
expect(response.parsed_body["success"]).to be(false)
expect(response).to be_forbidden
end
it "allows sellers to sign request for buckets they own" do
sign_string = "POST\n\nvideo/quicktime; charset=UTF-8\n\nx-amz-acl:private\nx-amz-date:Mon, 02 Mar 2015 17:21:19 \
GMT\n/gumroad-specs/attachments/#{seller.external_id}/bf03be06616f4dfd88da7c37005a9b2f/original/capturedvideo%20(1)-5-2.mov?uploads"
get :generate_multipart_signature, params: { to_sign: sign_string }
expect(response).to be_successful
end
end
describe "GET cdn_url_for_blob" do
it "returns blob cdn url with valid key" do
blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
get :cdn_url_for_blob, params: { key: blob.key }
expect(response).to redirect_to (cdn_url_for(blob.url))
end
it "404s with an invalid key" do
expect do
get :cdn_url_for_blob, params: { key: "xxx" }
end.to raise_error(ActionController::RoutingError)
end
it "returns the blob cdn url in JSON format" do
blob = ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "smilie.png")
get :cdn_url_for_blob, params: { key: blob.key }, format: :json
expect(response.parsed_body["url"]).to eq(cdn_url_for(blob.url))
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/discover_controller_spec.rb | spec/controllers/discover_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe DiscoverController do
render_views
let(:discover_domain_with_protocol) { UrlService.discover_domain_with_protocol }
before do
allow_any_instance_of(Link).to receive(:update_asset_preview)
@buyer = create(:user)
@product = create(:product, user: create(:user, name: "Gumstein"))
sign_in @buyer
end
describe "#index" do
it "displays navigation" do
sign_in @buyer
get :index
expect(response.body).to have_field "Search products"
end
it "renders the proper meta tags with no extra parameters" do
get :index
expect(response.body).to have_selector("title:contains('Gumroad')", visible: false)
expect(response.body).to have_selector("meta[property='og:type'][content='website']", visible: false)
expect(response.body).to have_selector("meta[property='og:description'][content='Browse over 1.6 million free and premium digital products in education, tech, design, and more categories from Gumroad creators and online entrepreneurs.']", visible: false)
expect(response.body).to have_selector("meta[name='description'][content='Browse over 1.6 million free and premium digital products in education, tech, design, and more categories from Gumroad creators and online entrepreneurs.']", visible: false)
expect(response.body).to have_selector("link[rel='canonical'][href='#{discover_domain_with_protocol}/']", visible: false)
end
it "renders the proper meta tags when a search query was submitted" do
get :index, params: { query: "tests" }
expect(response.body).to have_selector("title:contains('Gumroad')", visible: false)
expect(response.body).to have_selector("meta[property='og:description'][content='Browse over 1.6 million free and premium digital products in education, tech, design, and more categories from Gumroad creators and online entrepreneurs.']", visible: false)
expect(response.body).to have_selector("meta[name='description'][content='Browse over 1.6 million free and premium digital products in education, tech, design, and more categories from Gumroad creators and online entrepreneurs.']", visible: false)
expect(response.body).to have_selector("link[rel='canonical'][href='#{discover_domain_with_protocol}/?query=tests']", visible: false)
end
it "renders the proper meta tags when a specific tag has been selected" do
get :index, params: { tags: "3d models" }
description = "Browse over 0 3D assets including 3D models, CG textures, HDRI environments & more" \
" for VFX, game development, AR/VR, architecture, and animation."
expect(response.body).to have_selector("title:contains('Professional 3D Modeling Assets | Gumroad')", visible: false)
expect(response.body).to have_selector("meta[property='og:description'][content='#{description}']", visible: false)
expect(response.body).to have_selector("meta[name='description'][content='#{description}']", visible: false)
expect(response.body).to have_selector("link[rel='canonical'][href='#{discover_domain_with_protocol}/?tags=3d+models']", visible: false)
end
it "renders the proper meta tags when a specific tag has been selected" do
get :index, params: { tags: "3d - mODELs" }
description = "Browse over 0 3D assets including 3D models, CG textures, HDRI environments & more" \
" for VFX, game development, AR/VR, architecture, and animation."
expect(response.body).to have_selector("title:contains('Professional 3D Modeling Assets | Gumroad')", visible: false)
expect(response.body).to have_selector("meta[property='og:description'][content='#{description}']", visible: false)
expect(response.body).to have_selector("meta[name='description'][content='#{description}']", visible: false)
expect(response.body).to have_selector("link[rel='canonical'][href='#{discover_domain_with_protocol}/?tags=3d+models']", visible: false)
end
it "stores the search query" do
cookies[:_gumroad_guid] = "custom_guid"
expect do
get :index, params: { taxonomy: "3d/3d-modeling", query: "stl files" }
end.to change(DiscoverSearch, :count).by(1).and change(DiscoverSearchSuggestion, :count).by(1)
expect(DiscoverSearch.last!.attributes).to include(
"query" => "stl files",
"taxonomy_id" => Taxonomy.find_by_path(["3d", "3d-modeling"]).id,
"user_id" => @buyer.id,
"ip_address" => "0.0.0.0",
"browser_guid" => "custom_guid",
"autocomplete" => false
)
expect(DiscoverSearch.last!.discover_search_suggestion).to be_present
end
context "nav first render" do
it "renders as mobile if the user-agent is of an iPhone" do
@request.user_agent = "Mozilla/5.0 (iPhone; CPU OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Mobile/15E148 Safari/604.1"
get :index
expect(response.body).to have_selector("[role='nav'] > * > [aria-haspopup='menu'][aria-label='Categories']")
end
it "renders as desktop if the user-agent is windows chrome" do
@request.user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36."
get :index
expect(response.body).to have_selector("[role='nav'] > * > [role='menubar']")
end
end
context "meta description total count" do
let(:total_products) { Link::RECOMMENDED_PRODUCTS_PER_PAGE + 2 }
before do
total_products.times do |i|
product = create(:product, :recommendable)
product.tag!("3d models")
end
Link.import(refresh: true, force: true)
end
it "renders the correct total search result size in the meta description" do
get :index, params: { tags: "3d models" }
description = "Browse over #{total_products} 3D assets including 3D models, CG textures, HDRI environments & more" \
" for VFX, game development, AR/VR, architecture, and animation."
expect(response.body).to have_selector("meta[property='og:description'][content='#{description}']", visible: false)
expect(response.body).to have_selector("meta[name='description'][content='#{description}']", visible: false)
end
end
end
describe "#recommended_products" do
it "returns recommended products when taxonomy is blank" do
cart = create(:cart, user: @buyer)
create(:cart_product, cart:, product: @product)
recommended_product = create(:product)
expect(RecommendedProducts::DiscoverService).to receive(:fetch).with(
purchaser: @buyer,
cart_product_ids: [@product.id],
recommender_model_name: RecommendedProductsService::MODEL_SALES,
).and_return([RecommendedProducts::ProductInfo.new(recommended_product)])
get :recommended_products, format: :json
expect(response).to be_successful
expect(response.parsed_body).to eq([ProductPresenter.card_for_web(product: recommended_product, request:).as_json])
end
it "returns random products from all top taxonomies when taxonomy is blank and no curated products" do
top_taxonomies = Taxonomy.roots.to_a
all_top_products = []
top_taxonomies.each do |taxonomy|
products = create_list(:product, 3, :recommendable, taxonomy:)
all_top_products.concat(products)
end
Link.import(refresh: true, force: true)
allow(Rails.cache).to receive(:fetch).and_call_original
allow(Rails.cache).to receive(:fetch).with("discover_all_top_products", expires_in: 1.day).and_return(all_top_products)
sampled_products = all_top_products.first(DiscoverController::RECOMMENDED_PRODUCTS_COUNT)
allow(all_top_products).to receive(:sample).with(DiscoverController::RECOMMENDED_PRODUCTS_COUNT).and_return(sampled_products)
get :recommended_products, format: :json
expect(response).to be_successful
expected_products = sampled_products.map do |product|
ProductPresenter.card_for_web(
product:,
request:,
target: Product::Layout::DISCOVER,
recommended_by: RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION
).as_json
end
expect(response.parsed_body).to match_array(expected_products)
end
it "returns search results when taxonomy is present" do
taxonomy = Taxonomy.find_by!(slug: "3d")
other_taxonomy = Taxonomy.find_or_create_by!(slug: "other")
taxonomy_product = create(:product, :recommendable, taxonomy:)
child_taxonomy_product = create(:product, :recommendable, taxonomy: taxonomy.children.first)
create(:product, :recommendable, taxonomy: other_taxonomy)
Link.import(refresh: true, force: true)
get :recommended_products, params: { taxonomy: "3d" }, format: :json
expect(response).to be_successful
expect(response.parsed_body).to contain_exactly(
ProductPresenter.card_for_web(product: taxonomy_product, request:, target: Product::Layout::DISCOVER, recommended_by: RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION).as_json,
ProductPresenter.card_for_web(product: child_taxonomy_product, request:, target: Product::Layout::DISCOVER, recommended_by: RecommendationType::GUMROAD_DISCOVER_RECOMMENDATION).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/balance_controller_spec.rb | spec/controllers/balance_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 BalanceController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
before do
create_list(:payment_completed, 5, user: 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 }
let(:policy_method) { :index? }
end
it "assigns the correct instance variables and renders template" do
expect(UserBalanceStatsService).to receive(:new).with(user: seller).and_call_original
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Payouts/Index")
expect(inertia.props[:next_payout_period_data]).to eq({
should_be_shown_currencies_always: false,
minimum_payout_amount_cents: 1000,
is_user_payable: false,
status: "not_payable",
payout_note: nil,
has_stripe_connect: false
})
expect(inertia.props[:past_payout_period_data]).to be_present
expect(inertia.props[:pagination]).to be_present
end
context "with pagination" do
let(:payments_per_page) { 2 }
before do
stub_const("PayoutsPresenter::PAST_PAYMENTS_PER_PAGE", payments_per_page)
end
it "returns correct payouts for subsequent pages" do
get :index, params: { page: 2 }
expect(response).to be_successful
expect(inertia.props[:past_payout_period_data]).to be_an(Array)
expect(inertia.props[:past_payout_period_data].length).to eq(payments_per_page)
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/github_stars_controller_spec.rb | spec/controllers/github_stars_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe GithubStarsController do
describe "GET show", :vcr do
it "renders HTTP success" do
get :show
expect(response).to be_successful
expect(response.content_type).to include("application/json")
expect(response.parsed_body["stars"]).to eq(5818)
expect(response.headers["Cache-Control"]).to include("max-age=3600, public")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/bundles_controller_spec.rb | spec/controllers/bundles_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe BundlesController do
let(:seller) { create(:named_seller, :eligible_for_service_products) }
let(:bundle) { create(:product, :bundle, user: seller, price_cents: 2000) }
include_context "with user signed in as admin for seller"
describe "GET show" do
render_views
it "initializes the presenter with the correct arguments and sets the title to the bundle's name" do
expect(BundlePresenter).to receive(:new).with(bundle:).and_call_original
get :show, params: { id: bundle.external_id }
expect(response.body).to have_selector("title:contains('#{bundle.name}')", visible: false)
expect(response).to be_successful
end
context "when the bundle doesn't exist" do
it "returns 404" do
expect { get :show, params: { id: "" } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "product is membership" do
let(:product) { create(:membership_product) }
it "returns 404" do
expect { get :show, params: { id: product.external_id } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "product has variants" do
let(:product) { create(:product_with_digital_versions) }
it "returns 404" do
expect { get :show, params: { id: product.external_id } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
end
describe "GET create_from_email" do
let!(:product) { create(:product, user: seller) }
let!(:versioned_product) { create(:product_with_digital_versions, user: seller) }
it_behaves_like "authorize called for action", :get, :create_from_email do
let(:policy_klass) { LinkPolicy }
let(:record) { Link }
let(:policy_method) { :create? }
end
it "creates the bundle and redirects to the edit page" do
get :create_from_email, params: { type: Product::BundlesMarketing::BEST_SELLING_BUNDLE, price: 100, products: [product.external_id, versioned_product.external_id] }
bundle = Link.last
expect(response).to redirect_to bundle_path(bundle.external_id)
expect(bundle.name).to eq("Best Selling Bundle")
expect(bundle.price_cents).to eq(100)
expect(bundle.is_bundle).to eq(true)
expect(bundle.from_bundle_marketing).to eq(true)
expect(bundle.native_type).to eq(Link::NATIVE_TYPE_BUNDLE)
expect(bundle.price_currency_type).to eq(Currency::USD)
bundle_product1 = bundle.bundle_products.first
expect(bundle_product1.product).to eq(product)
expect(bundle_product1.variant).to be_nil
expect(bundle_product1.quantity).to eq(1)
bundle_product2 = bundle.bundle_products.second
expect(bundle_product2.product).to eq(versioned_product)
expect(bundle_product2.variant).to eq(versioned_product.alive_variants.first)
expect(bundle_product2.quantity).to eq(1)
end
end
describe "GET products" do
let!(:product) { create(:product, user: seller, name: "Product") }
let!(:versioned_product) { create(:product_with_digital_versions, name: "Versioned product", user: seller) }
let!(:bundle_product) { create(:product, :bundle, user: seller, name: "Bundle product") }
let!(:membership_product) { create(:membership_product_with_preset_tiered_pricing, user: seller, name: "Membership product") }
let!(:call_product) { create(:call_product, user: seller, name: "Call product") }
let!(:archived_product) { create(:product, user: seller, name: "Archived product", archived: true) }
before do
index_model_records(Link)
stub_const("BundlesController::PER_PAGE", 1)
end
it_behaves_like "authorize called for action", :get, :products do
let(:policy_klass) { LinkPolicy }
let(:record) { Link }
let(:policy_method) { :index? }
end
it "returns products that can be added to a bundle" do
get :products, params: { all: true, product_id: bundle_product.bundle_products.first.product.external_id }
ids = response.parsed_body["products"].map { _1["id"] }
expect(ids).to match_array([product, versioned_product, archived_product, bundle_product.bundle_products.second.product].map(&:external_id))
end
end
describe "PUT update" do
let(:product) { create(:product, user: seller) }
let(:asset_previews) { create_list(:asset_preview, 2, link: bundle) }
let(:versioned_product) { create(:product_with_digital_versions, user: seller) }
let(:profile_section1) { create(:seller_profile_products_section, seller:, shown_products: [bundle.id]) }
let(:profile_section2) { create(:seller_profile_products_section, seller:) }
let!(:purchase) { create(:purchase, link: bundle) }
let(:bundle_params) do
{
id: bundle.external_id,
name: "New name",
description: "New description",
custom_permalink: "new-permalink",
price_cents: 1000,
customizable_price: true,
suggested_price_cents: 2000,
custom_button_text_option: "buy_this_prompt",
custom_summary: "Custom summary",
custom_attributes: [{ "name" => "Detail 1", "value" => "Value 1" }],
covers: [asset_previews.second.guid, asset_previews.first.guid],
max_purchase_count: 10,
quantity_enabled: true,
should_show_sales_count: true,
taxonomy_id: 1,
tags: ["tag1", "tag2", "tag3"],
display_product_reviews: false,
is_adult: true,
discover_fee_per_thousand: 400,
is_epublication: true,
product_refund_policy_enabled: true,
refund_policy: {
title: "New refund policy",
fine_print: "I really hate being small",
},
section_ids: [profile_section2.external_id],
products: [
{
product_id: bundle.bundle_products.first.product.external_id,
variant_id: nil,
quantity: 3,
},
{
product_id: product.external_id,
quantity: 1,
},
{
product_id: versioned_product.external_id,
variant_id: versioned_product.alive_variants.first.external_id,
quantity: 2,
}
]
}
end
it_behaves_like "authorize called for action", :put, :update do
let(:policy_klass) { LinkPolicy }
let(:record) { bundle }
let(:request_params) { { id: bundle.external_id } }
end
before { index_model_records(Purchase) }
it "updates the bundle" do
expect do
put :update, params: bundle_params, as: :json
bundle.reload
end.to change { bundle.name }.from("Bundle").to("New name")
.and change { bundle.description }.from("This is a bundle of products").to("New description")
.and change { bundle.custom_permalink }.from(nil).to("new-permalink")
.and change { bundle.price_cents }.from(2000).to(1000)
.and change { bundle.customizable_price? }.from(false).to(true)
.and change { bundle.suggested_price_cents }.from(nil).to(2000)
.and change { bundle.custom_button_text_option }.from(nil).to("buy_this_prompt")
.and change { bundle.custom_attributes }.from([]).to([{ "name" => "Detail 1", "value" => "Value 1" }])
.and change { bundle.custom_summary }.from(nil).to("Custom summary")
.and change { bundle.display_asset_previews.map(&:id) }.from([asset_previews.first.id, asset_previews.second.id]).to([asset_previews.second.id, asset_previews.first.id])
.and change { bundle.max_purchase_count }.from(nil).to(10)
.and change { bundle.quantity_enabled }.from(false).to(true)
.and change { bundle.should_show_sales_count }.from(false).to(true)
.and change { bundle.taxonomy_id }.from(nil).to(1)
.and change { bundle.tags.pluck(:name) }.from([]).to(["tag1", "tag2", "tag3"])
.and change { bundle.display_product_reviews }.from(true).to(false)
.and change { bundle.is_adult }.from(false).to(true)
.and change { bundle.discover_fee_per_thousand }.from(100).to(400)
.and change { bundle.is_epublication }.from(false).to(true)
.and not_change { bundle.product_refund_policy_enabled }
.and not_change { bundle.product_refund_policy&.title }
.and not_change { bundle.product_refund_policy&.fine_print }
.and change { bundle.has_outdated_purchases }.from(false).to(true)
.and change { profile_section1.reload.shown_products }.from([bundle.id]).to([])
.and change { profile_section2.reload.shown_products }.from([]).to([bundle.id])
expect(response).to be_successful
deleted_bundle_products = bundle.bundle_products.deleted
expect(deleted_bundle_products.first.deleted_at).to be_present
new_bundle_products = bundle.bundle_products.alive
expect(new_bundle_products.first.product).to eq(bundle.bundle_products.first.product)
expect(new_bundle_products.first.variant).to be_nil
expect(new_bundle_products.first.bundle).to eq(bundle)
expect(new_bundle_products.first.quantity).to eq(3)
expect(new_bundle_products.first.deleted_at).to be_nil
expect(new_bundle_products.second.product).to eq(product)
expect(new_bundle_products.second.variant).to be_nil
expect(new_bundle_products.second.bundle).to eq(bundle)
expect(new_bundle_products.second.quantity).to eq(1)
expect(new_bundle_products.second.deleted_at).to be_nil
expect(new_bundle_products.third.product).to eq(versioned_product)
expect(new_bundle_products.third.variant).to eq(versioned_product.alive_variants.first)
expect(new_bundle_products.third.bundle).to eq(bundle)
expect(new_bundle_products.third.quantity).to eq(2)
expect(new_bundle_products.third.deleted_at).to be_nil
end
describe "installment plans" do
let(:bundle_params) { super().merge(customizable_price: false) }
let(:commission_product) { create(:commission_product, user: seller) }
let(:course_product) { create(:product, native_type: Link::NATIVE_TYPE_COURSE, user: seller) }
let(:digital_product) { create(:product, native_type: Link::NATIVE_TYPE_DIGITAL, user: seller) }
context "when bundle is eligible for installment plans" do
context "with no existing plans" do
it "creates a new installment plan" do
params = bundle_params.merge(installment_plan: { number_of_installments: 3 })
expect { put :update, params: params, as: :json }
.to change { ProductInstallmentPlan.alive.count }.by(1)
plan = bundle.reload.installment_plan
expect(plan.number_of_installments).to eq(3)
expect(plan.recurrence).to eq("monthly")
expect(response.status).to eq(204)
end
end
context "with an existing plan" do
let!(:existing_plan) do
create(
:product_installment_plan,
link: bundle,
number_of_installments: 2,
)
end
it "does not allow adding products that are not eligible for installment plans" do
params = bundle_params.merge(
installment_plan: { number_of_installments: 2 },
products: [
{
product_id: commission_product.external_id,
quantity: 1
},
]
)
expect { put :update, params: params, as: :json }
.not_to change { bundle.bundle_products.count }
expect(response.status).to eq(422)
expect(response.parsed_body["error_message"]).to include("Installment plan is not available for the bundled product")
expect(bundle.reload.bundle_products.map(&:product)).not_to include(commission_product)
end
context "with no existing payment options" do
it "destroys the existing plan and creates a new plan" do
params = bundle_params.merge(installment_plan: { number_of_installments: 4 })
expect { put :update, params: params, as: :json }
.not_to change { ProductInstallmentPlan.count }
expect { existing_plan.reload }.to raise_error(ActiveRecord::RecordNotFound)
new_plan = bundle.reload.installment_plan
expect(new_plan).to have_attributes(
number_of_installments: 4,
recurrence: "monthly"
)
expect(response.status).to eq(204)
end
end
context "with existing payment options" do
before do
create(:payment_option, installment_plan: existing_plan)
create(:installment_plan_purchase, link: bundle)
end
it "soft deletes the existing plan and creates a new plan" do
params = bundle_params.merge(installment_plan: { number_of_installments: 4 })
expect { put :update, params: params, as: :json }
.to change { existing_plan.reload.deleted_at }.from(nil)
new_plan = bundle.reload.installment_plan
expect(new_plan).to have_attributes(
number_of_installments: 4,
recurrence: "monthly"
)
expect(new_plan).not_to eq(existing_plan)
expect(response.status).to eq(204)
end
end
end
context "removing an existing plan" do
let!(:existing_plan) do
create(
:product_installment_plan,
link: bundle,
number_of_installments: 2,
recurrence: "monthly"
)
end
context "with no existing payment options" do
it "destroys the existing plan" do
params = bundle_params.merge(installment_plan: nil)
expect { put :update, params: params, as: :json }
.to change { ProductInstallmentPlan.count }.by(-1)
expect { existing_plan.reload }.to raise_error(ActiveRecord::RecordNotFound)
expect(bundle.reload.installment_plan).to be_nil
expect(response.status).to eq(204)
end
end
context "with existing payment options" do
before do
create(:payment_option, installment_plan: existing_plan)
create(:installment_plan_purchase, link: bundle)
end
it "soft deletes the existing plan" do
params = bundle_params.merge(installment_plan: nil)
expect { put :update, params: params, as: :json }
.to change { existing_plan.reload.deleted_at }.from(nil)
expect(bundle.reload.installment_plan).to be_nil
expect(response.status).to eq(204)
end
end
end
end
context "when bundle is not eligible for installment plans" do
let!(:bundle_product) { create(:bundle_product, bundle: bundle, product: commission_product) }
it "does not create an installment plan" do
params = bundle_params.merge(installment_plan: { number_of_installments: 3 })
expect { put :update, params: params, as: :json }
.not_to change { ProductInstallmentPlan.count }
expect(bundle.reload.installment_plan).to be_nil
expect(response.status).to eq(422)
expect(response.parsed_body["error_message"]).to include("Installment plan is not available for the bundled product")
end
end
context "when bundle has customizable price" do
before { bundle.update!(customizable_price: true) }
it "does not create an installment plan" do
params = bundle_params.merge(
customizable_price: true,
installment_plan: { number_of_installments: 3 }
)
expect { put :update, params: params, as: :json }
.not_to change { ProductInstallmentPlan.count }
expect(bundle.reload.installment_plan).to be_nil
expect(response.status).to eq(422)
expect(response.parsed_body["error_message"]).to include("Installment plans are not available for \"pay what you want\" pricing")
end
end
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 bundle refund policy" do
put :update, params: bundle_params, as: :json
bundle.reload
expect(bundle.product_refund_policy_enabled).to be(true)
expect(bundle.product_refund_policy.title).to eq("30-day money back guarantee")
expect(bundle.product_refund_policy.fine_print).to eq("I really hate being small")
end
end
context "when seller refund policy is set to false" do
before do
seller.update!(refund_policy_enabled: false)
end
it "updates the bundle refund policy" do
put :update, params: bundle_params, as: :json
bundle.reload
expect(bundle.product_refund_policy_enabled).to be(true)
expect(bundle.product_refund_policy.title).to eq("30-day money back guarantee")
expect(bundle.product_refund_policy.fine_print).to eq("I really hate being small")
end
context "with bundle refund policy enabled" do
before do
bundle.update!(product_refund_policy_enabled: true)
end
it "disables the product refund policy" do
bundle_params[:product_refund_policy_enabled] = false
put :update, params: bundle_params, as: :json
bundle.reload
expect(bundle.product_refund_policy_enabled).to be(false)
expect(bundle.product_refund_policy).to be_nil
end
end
end
context "adding a call to a bundle" do
let(:call_product) { create(:call_product, user: seller) }
it "does not make any changes to the bundle and returns an error" do
expect do
put :update, params: {
id: bundle.external_id,
products: [
{
product_id: call_product.external_id,
variant_id: call_product.variants.first.external_id,
quantity: 1
},
{ product_id: product.external_id, quantity: 1, },
]
}
bundle.reload
end.to_not change { bundle.bundle_products.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["error_message"]).to eq("Validation failed: A call product cannot be added to a bundle")
end
end
context "product is not a bundle" do
let(:product) { create(:product, user: seller) }
it "converts it to a bundle" do
expect do
put :update, params: {
id: product.external_id,
products: [
{
product_id: versioned_product.external_id,
variant_id: versioned_product.alive_variants.first.external_id,
quantity: 1,
},
]
}
product.reload
end.to change { product.is_bundle }.from(false).to(true)
.and change { product.native_type }.from(Link::NATIVE_TYPE_DIGITAL).to(Link::NATIVE_TYPE_BUNDLE)
expect(product.bundle_products.count).to eq(1)
expect(product.bundle_products.first.product).to eq(versioned_product)
expect(product.bundle_products.first.variant).to eq(versioned_product.alive_variants.first)
expect(product.bundle_products.first.quantity).to eq(1)
end
end
context "when there is a validation error" do
it "returns the error message" do
expect do
put :update, params: {
id: bundle.external_id,
custom_permalink: "*",
bundle_products: [],
}, as: :json
end.to change { bundle.bundle_products.count }.by(0)
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["error_message"]).to eq("Custom permalink is invalid")
end
end
context "when the bundle doesn't exist" do
it "returns 404" do
expect { put :update, params: { id: "" } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "product is a call" do
let(:product) { create(:call_product) }
it "returns 404" do
expect { put :update, params: { id: product.external_id } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "product is membership" do
let(:product) { create(:membership_product) }
it "returns 404" do
expect { put :update, params: { id: product.external_id } }.to raise_error(ActiveRecord::RecordNotFound)
end
end
context "product has variants" do
let(:product) { create(:product_with_digital_versions) }
it "returns 404" do
expect { put :update, params: { id: product.external_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/communities_controller_spec.rb | spec/controllers/communities_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe CommunitiesController do
let(:seller) { create(:user) }
let(:pundit_user) { SellerContext.new(user: seller, seller:) }
let(:product) { create(:product, user: seller, community_chat_enabled: true) }
let!(:community) { create(:community, seller:, resource: product) }
include_context "with user signed in as admin for seller"
before do
Feature.activate_user(:communities, seller)
end
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { Community }
end
context "when seller is logged in" do
before do
sign_in seller
end
it "renders the page" do
get :index
expect(response).to be_successful
expect(assigns(:title)).to eq("Communities")
end
it "returns unauthorized response if the :communities feature flag is disabled" do
Feature.deactivate_user(:communities, seller)
get :index
expect(response).to redirect_to dashboard_path
expect(flash[:alert]).to eq("You are not allowed to perform this action.")
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/concerns/current_api_user_spec.rb | spec/controllers/concerns/current_api_user_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CurrentApiUser, type: :controller do
controller(ApplicationController) do
include CurrentApiUser
skip_before_action :set_signup_referrer
def action
head :ok
end
end
before do
routes.draw { match :action, to: "anonymous#action", via: [:get, :post] }
end
describe "#current_api_user" do
context "without a doorkeeper token" do
it "returns nil" do
get :action
expect(controller.current_api_user).to be(nil)
end
end
context "with a valid doorkeeper token" do
let(:user) { create(:user) }
let(:application) { create(:oauth_application) }
let(:access_token) do
create(
"doorkeeper/access_token",
application:,
resource_owner_id: user.id,
scopes: "creator_api"
).token
end
let(:params) do
{
mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
access_token:
}
end
it "returns the user associated with the token" do
get(:action, params:)
expect(controller.current_api_user).to eq(user)
end
end
context "with an invalid doorkeeper token" do
let(:access_token) { "invalid" }
before do
@request.params["access_token"] = access_token
end
it "returns nil" do
get :action
expect(controller.current_api_user).to be(nil)
end
end
it "does not error with invalid POST data" do
post :action, body: '{ "abc"#012: "xyz" }', as: :json
expect(controller.current_api_user).to eq(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/throttling_spec.rb | spec/controllers/concerns/throttling_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Throttling, type: :request do
let(:anonymous_controller) do
Class.new(ApplicationController) do
include Throttling
before_action :test_throttle
def test_action
render json: { success: true }
end
private
def test_throttle
throttle!(key: "test_key", limit: 5, period: 1.hour)
end
end
end
let(:redis) { $redis }
before do
redis.del("test_key")
Rails.application.routes.draw do
get "test_throttle", to: "anonymous#test_action"
end
stub_const("AnonymousController", anonymous_controller)
end
after do
Rails.application.reload_routes!
end
describe "#throttle!" do
it "allows requests within the limit" do
get "/test_throttle"
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)["success"]).to be true
end
it "blocks requests when limit is exceeded" do
# Make 5 requests (the limit)
5.times do
get "/test_throttle"
expect(response).to have_http_status(:ok)
end
# The 6th request should be blocked
get "/test_throttle"
expect(response).to have_http_status(:too_many_requests)
expect(JSON.parse(response.body)["error"]).to match(/Rate limit exceeded/)
expect(response.headers["Retry-After"]).to be_present
end
it "sets expiration on first request" do
get "/test_throttle"
ttl = redis.ttl("test_key")
expect(ttl).to be > 0
expect(ttl).to be <= 3600
end
it "does not reset expiration on subsequent requests" do
get "/test_throttle"
initial_ttl = redis.ttl("test_key")
# Manually reduce TTL to simulate time passing
redis.expire("test_key", initial_ttl - 1)
# Second request should not reset expiration
get "/test_throttle"
second_ttl = redis.ttl("test_key")
expect(second_ttl).to be < initial_ttl
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/pundit_authorization_spec.rb | spec/controllers/concerns/pundit_authorization_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
describe PunditAuthorization, type: :controller do
class DummyPolicy < ApplicationPolicy
def action?
false
end
end
# Does not inherit from ApplicationPolicy
class PublicDummyPolicy
def initialize(_context, _record)
end
def public_action?
false
end
end
controller(ApplicationController) do
include PunditAuthorization
before_action :authenticate_user!, only: [:action]
after_action :verify_authorized
def action
authorize :dummy
head :ok
end
def public_action
authorize :public_dummy
head :ok
end
end
before do
routes.draw do
get :action, to: "anonymous#action"
get :public_action, to: "anonymous#public_action"
end
end
let(:seller) { create(:named_seller) }
describe "pundit_user" do
include_context "with user signed in as admin for seller"
it "sets correct values to SellerContext" do
get :action
seller_context = controller.pundit_user
expect(seller_context.user).to eq(user_with_role_for_seller)
expect(seller_context.seller).to eq(seller)
end
end
describe "user_not_authorized" do
context "with action that requires authentication" do
include_context "with user signed in as admin for seller"
context "with JSON request" do
it "logs and renders JSON response" do
expect(Rails.logger).to receive(:warn).with(
"Pundit::NotAuthorizedError for DummyPolicy by User ID #{user_with_role_for_seller.id} for Seller ID #{seller.id}: not allowed to action? this Symbol"
)
get :action, format: :json
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("Your current role as Admin cannot perform this action.")
end
end
context "with JS request" do
it "logs and renders JSON response" do
expect(Rails.logger).to receive(:warn).with(
"Pundit::NotAuthorizedError for DummyPolicy by User ID #{user_with_role_for_seller.id} for Seller ID #{seller.id}: not allowed to action? this Symbol"
)
get :action, xhr: true
expect(response).to have_http_status(:unauthorized)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("Your current role as Admin cannot perform this action.")
end
end
context "with non-JSON request" do
it "logs and redirects" do
expect(Rails.logger).to receive(:warn).with(
"Pundit::NotAuthorizedError for DummyPolicy by User ID #{user_with_role_for_seller.id} for Seller ID #{seller.id}: not allowed to action? this Symbol"
)
get :action
expect(response).to redirect_to dashboard_path
expect(flash[:alert]).to eq("Your current role as Admin cannot perform this action.")
end
context "when account_switched param is present" do
it "redirects without logging and without flash message" do
expect(Rails.logger).not_to receive(:warn).with(
"Pundit::NotAuthorizedError for DummyPolicy by User ID #{user_with_role_for_seller.id} for Seller ID #{seller.id}: not allowed to action? this Symbol"
)
get :action, params: { account_switched: "true" }
expect(response).to redirect_to dashboard_path
expect(flash[:alert]).not_to eq("Your current role as Admin cannot perform this action.")
end
end
end
end
context "with action that does not require authentication" do
it "returns a generic error message" do
expect(Rails.logger).to receive(:warn).with(
"Pundit::NotAuthorizedError for PublicDummyPolicy by unauthenticated user: not allowed to public_action? this Symbol"
)
get :public_action, format: :json
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
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/csrf_token_injector_spec.rb | spec/controllers/concerns/csrf_token_injector_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CsrfTokenInjector, type: :controller do
controller do
include CsrfTokenInjector
def action
html_body = <<-HTML
<html>
<head>
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__">
</head>
<body></body>
</html>
HTML
render inline: html_body
end
end
before do
routes.draw { get :action, to: "anonymous#action" }
# mocking here instead of including `protect_from_forgery` in the anonymous controller because protection against forgery is disabled in test environment
allow_any_instance_of(ActionController::Base).to receive(:protect_against_forgery?).and_return(true)
end
it "replaces CSRF token placeholder with dynamic value" do
get :action
expect(response.body).not_to include("_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__")
expect(Nokogiri::HTML(response.body).at_xpath("//meta[@name='csrf-token']/@content").value).to be_present
end
describe "CSRF token exfiltration prevention" do
controller do
include CsrfTokenInjector
def action_with_user_content
user_bio = '<img src="https://evil.com/exfil?t=_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__">'
html_body = <<-HTML
<html>
<head>
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__">
</head>
<body>
<div class="user-bio">#{user_bio}</div>
</body>
</html>
HTML
render inline: html_body
end
end
before do
routes.draw { get :action_with_user_content, to: "anonymous#action_with_user_content" }
allow_any_instance_of(ActionController::Base).to receive(:protect_against_forgery?).and_return(true)
end
it "does not replace placeholder in user-controlled content" do
get :action_with_user_content
doc = Nokogiri::HTML(response.body)
meta_token = doc.at_xpath("//meta[@name='csrf-token']/@content").value
expect(meta_token).to be_present
expect(meta_token).not_to eq("_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__")
user_bio_content = doc.at_css(".user-bio").inner_html
expect(user_bio_content).to include("_CROSS_SITE_REQUEST_FORGERY_PROTECTION_TOKEN__")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/two_factor_authentication_validator_spec.rb | spec/controllers/concerns/two_factor_authentication_validator_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe TwoFactorAuthenticationValidator, type: :controller do
controller(ApplicationController) do
before_action :authenticate_user!
include TwoFactorAuthenticationValidator
def action
head :ok
end
end
before do
routes.draw { get :action, to: "anonymous#action" }
end
before do
@user = create(:user, skip_enabling_two_factor_authentication: false)
sign_in @user
end
describe "#skip_two_factor_authentication?" do
context "when two factor authentication is disabled for the user" do
before do
@user.two_factor_authentication_enabled = false
@user.save!
end
it "returns true" do
expect(controller.skip_two_factor_authentication?(@user)).to eq true
end
end
context "when a valid two factor cookie is present" do
before do
cookie_hash = { @user.two_factor_authentication_cookie_key => "#{@user.id},#{5.minutes.from_now.to_i}" }
encrypted_cookie_jar = OpenStruct.new({ encrypted: cookie_hash })
allow(controller).to receive(:cookies).and_return(encrypted_cookie_jar)
end
it "returns true" do
expect(controller.skip_two_factor_authentication?(@user)).to eq true
end
it "extends the cookie expiry" do
expect(controller).to receive(:set_two_factor_auth_cookie).and_call_original
controller.skip_two_factor_authentication?(@user)
end
end
context "when the user has verified two factor auth from that IP before" do
before do
@user.add_two_factor_authenticated_ip!("0.0.0.0")
end
it "returns true" do
expect(controller.skip_two_factor_authentication?(@user)).to eq true
end
end
end
describe "#set_two_factor_auth_cookie" do
it "sets the two factor auth cookie" do
travel_to(Time.current) do
controller.set_two_factor_auth_cookie(@user)
expires_at = 2.months.from_now.to_i
cookie_value = "#{@user.id},#{expires_at}"
cookies_encrypted = controller.send(:cookies).encrypted
expect(cookies_encrypted[@user.two_factor_authentication_cookie_key]).to eq cookie_value
end
end
end
describe "#remember_two_factor_auth" do
it "invokes #set_two_factor_auth_cookie" do
expect(controller).to receive(:set_two_factor_auth_cookie).and_call_original
controller.remember_two_factor_auth
end
it "remembers the two factor authenticated IP" do
expect_any_instance_of(User).to receive(:add_two_factor_authenticated_ip!).with("0.0.0.0").and_call_original
controller.remember_two_factor_auth
end
end
describe "#valid_two_factor_cookie_present?" do
context "when valid cookie is present" do
before do
cookie_hash = { @user.two_factor_authentication_cookie_key => "#{@user.id},#{5.minutes.from_now.to_i}" }
encrypted_cookie_jar = OpenStruct.new({ encrypted: cookie_hash })
allow(controller).to receive(:cookies).and_return(encrypted_cookie_jar)
end
it "returns true" do
expect(controller.send(:valid_two_factor_cookie_present?, @user)).to eq true
end
end
context "when valid cookie is not present" do
context "when cookie is missing" do
it "returns false" do
expect(controller.send(:valid_two_factor_cookie_present?, @user)).to eq false
end
end
context "when the timestamp in cookie is expired" do
before do
cookie_hash = { @user.two_factor_authentication_cookie_key => "#{@user.id},#{5.minutes.ago.to_i}" }
encrypted_cookie_jar = OpenStruct.new({ encrypted: cookie_hash })
allow(controller).to receive(:cookies).and_return(encrypted_cookie_jar)
end
it "returns false" do
expect(controller.send(:valid_two_factor_cookie_present?, @user)).to eq false
end
end
end
end
describe "#prepare_for_two_factor_authentication" do
it "sets user_id in session" do
controller.prepare_for_two_factor_authentication(@user)
expect(session[:verify_two_factor_auth_for]).to eq @user.id
end
context "when params[:next] contains 2FA verification URL" do
before do
allow(controller).to receive(:params).and_return({ next: verify_two_factor_authentication_path(format: :html) })
end
it "doesn't send authentication token" do
expect do
controller.prepare_for_two_factor_authentication(@user)
end.not_to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).with(@user.id)
end
end
context "when params[:next] doesn't contain 2FA verification URL" do
it "sends authentication token" do
expect do
controller.prepare_for_two_factor_authentication(@user)
end.to have_enqueued_mail(TwoFactorAuthenticationMailer, :authentication_token).with(@user.id)
end
end
end
describe "#user_for_two_factor_authentication" do
before do
controller.prepare_for_two_factor_authentication(@user)
end
it "gets the user from session" do
expect(controller.user_for_two_factor_authentication).to eq @user
end
end
describe "#reset_two_factor_auth_login_session" do
before do
controller.prepare_for_two_factor_authentication(@user)
end
it "removes the user_id from session" do
controller.reset_two_factor_auth_login_session
expect(session[:verify_two_factor_auth_for]).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/concerns/search_products_spec.rb | spec/controllers/concerns/search_products_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe SearchProducts do
# Create a test controller that includes the concern
controller(ApplicationController) do
include SearchProducts
def index
format_search_params!
render json: params
end
end
describe "#format_search_params!" do
context "with offer_code parameter" do
context "when feature flag is active" do
before do
Feature.activate(:offer_codes_search)
routes.draw { get "index" => "anonymous#index" }
end
after do
Feature.deactivate(:offer_codes_search)
end
it "preserves allowed offer code" do
get :index, params: { offer_code: "BLACKFRIDAY2025" }
expect(JSON.parse(response.body)["offer_code"]).to eq("BLACKFRIDAY2025")
end
it "returns __no_match__ when code is not allowed" do
get :index, params: { offer_code: "SUMMER2025" }
expect(JSON.parse(response.body)["offer_code"]).to eq("__no_match__")
end
end
context "when feature flag is inactive" do
before do
Feature.deactivate(:offer_codes_search)
routes.draw { get "index" => "anonymous#index" }
end
it "blocks offer_code when feature is disabled and no secret key" do
get :index, params: { offer_code: "BLACKFRIDAY2025" }
expect(JSON.parse(response.body)["offer_code"]).to eq("__no_match__")
end
context "with secret key" do
before do
ENV["SECRET_FEATURE_KEY"] = "test_secret_key_123"
end
after do
ENV.delete("SECRET_FEATURE_KEY")
end
it "allows offer_code when valid secret key is provided" do
get :index, params: { offer_code: "BLACKFRIDAY2025", feature_key: "test_secret_key_123" }
expect(JSON.parse(response.body)["offer_code"]).to eq("BLACKFRIDAY2025")
end
it "blocks offer_code when invalid secret key is provided" do
get :index, params: { offer_code: "BLACKFRIDAY2025", feature_key: "wrong_key" }
expect(JSON.parse(response.body)["offer_code"]).to eq("__no_match__")
end
it "blocks offer_code when secret key is empty" do
get :index, params: { offer_code: "BLACKFRIDAY2025", feature_key: "" }
expect(JSON.parse(response.body)["offer_code"]).to eq("__no_match__")
end
it "blocks non-allowed offer_code even with valid secret key" do
get :index, params: { offer_code: "SUMMER2025", feature_key: "test_secret_key_123" }
expect(JSON.parse(response.body)["offer_code"]).to eq("__no_match__")
end
end
end
end
context "without offer_code parameter" do
before do
routes.draw { get "index" => "anonymous#index" }
end
it "does not modify params when offer_code is not present" do
get :index, params: { tags: "design" }
expect(JSON.parse(response.body)["offer_code"]).to be_nil
end
end
context "with other parameters" do
before do
routes.draw { get "index" => "anonymous#index" }
end
it "parses tags from string" do
get :index, params: { tags: "design,art" }
expect(JSON.parse(response.body)["tags"]).to eq(["design", "art"])
end
it "parses filetypes from string" do
get :index, params: { filetypes: "pdf,video" }
expect(JSON.parse(response.body)["filetypes"]).to eq(["pdf", "video"])
end
it "converts size to integer" do
get :index, params: { size: "20" }
expect(JSON.parse(response.body)["size"]).to eq(20)
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/concerns/impersonate_spec.rb | spec/controllers/concerns/impersonate_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Impersonate, type: :controller do
controller(ApplicationController) do
include Impersonate
def action
head :ok
end
end
before do
routes.draw { get :action, to: "anonymous#action" }
end
context "when not authenticated" do
it "returns appropriate values" do
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to be(nil)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to be(nil)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
let(:user) { create(:named_user) }
context "when authenticated as admin" do
let(:admin) { create(:named_user, :admin) }
describe "for web" do
before do
sign_in admin
end
describe "#impersonate_user" do
context "when not impersonating" do
it "returns appropriate values" do
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to eq(admin)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to eq(admin)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
context "when impersonating" do
it "impersonates" do
controller.impersonate_user(user)
get :action
expect(controller.impersonating?).to eq(true)
expect(controller.current_user).to eq(admin)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to eq(user)
expect(controller.impersonating_user).to eq(admin)
expect(controller.impersonated_user).to eq(user)
end
context "when the user is deleted" do
before do
controller.impersonate_user(user)
user.deactivate!
end
it "doesn't impersonate" do
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to eq(admin)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to eq(admin)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
end
end
describe "#stop_impersonating_user" do
before do
controller.impersonate_user(user)
expect(controller.impersonating?).to eq(true)
end
it "stops impersonating" do
controller.stop_impersonating_user
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to eq(admin)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to eq(admin)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
describe "#impersonated_user" do
context "when not impersonating" do
it "returns nil" do
get :action
expect(controller.impersonated_user).to be(nil)
end
end
context "when impersonating" do
before do
controller.impersonate_user(user)
end
it "returns the user" do
get :action
expect(controller.impersonated_user).to eq(user)
end
context "when the user is deleted" do
before do
user.deactivate!
end
it "returns nil" do
get :action
expect(controller.impersonated_user).to be(nil)
end
end
context "when the user is suspended for fraud" do
before do
user.flag_for_fraud!(author_id: admin.id)
user.suspend_for_fraud!(author_id: admin.id)
end
it "returns nil" do
get :action
expect(controller.impersonated_user).to be(nil)
end
end
context "when the user is suspended for ToS violation" do
before do
user.flag_for_tos_violation!(author_id: admin.id, product_id: create(:product, user:).id)
user.suspend_for_tos_violation!(author_id: admin.id)
end
it "returns nil" do
get :action
expect(controller.impersonated_user).to be(nil)
end
end
end
end
end
describe "for mobile API" do
let(:application) { create(:oauth_application) }
let(:access_token) do
create(
"doorkeeper/access_token",
application:,
resource_owner_id: admin.id,
scopes: "creator_api"
).token
end
let(:params) do
{
mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
access_token:
}
end
before do
@request.params["access_token"] = access_token
end
describe "#impersonate_user" do
it "impersonates user" do
controller.impersonate_user(user)
get :action
expect(controller.impersonating?).to eq(true)
expect(controller.current_user).to be(nil)
expect(controller.current_api_user).to eq(admin)
expect(controller.logged_in_user).to eq(user)
expect(controller.impersonating_user).to eq(admin)
expect(controller.impersonated_user).to eq(user)
end
end
describe "#stop_impersonating_user" do
before do
controller.impersonate_user(user)
expect(controller.impersonating?).to eq(true)
end
it "stops impersonating user" do
controller.stop_impersonating_user
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to be(nil)
expect(controller.current_api_user).to eq(admin)
expect(controller.logged_in_user).to be(nil)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
end
end
context "when authenticated as regular user" do
let(:other_user) { create(:named_user) }
before do
sign_in other_user
controller.impersonate_user(user)
end
it "doesn't impersonate" do
get :action
expect(controller.impersonating?).to eq(false)
expect(controller.current_user).to eq(other_user)
expect(controller.current_api_user).to be(nil)
expect(controller.logged_in_user).to eq(other_user)
expect(controller.impersonating_user).to eq(nil)
expect(controller.impersonated_user).to eq(nil)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/admin_action_tracker_spec.rb | spec/controllers/concerns/admin_action_tracker_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe AdminActionTracker do
controller do
include AdminActionTracker
def index
head :ok
end
end
before do
routes.draw { get :index, to: "anonymous#index" }
end
it "calling an action increments the call_count" do
record = create(:admin_action_call_info, controller_name: "AnonymousController", action_name: "index")
get :index
expect(record.reload.call_count).to eq(1)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/utm_link_tracking_spec.rb | spec/controllers/concerns/utm_link_tracking_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe UtmLinkTracking, type: :controller do
controller(ApplicationController) do
include UtmLinkTracking
def action
head :ok
end
end
let(:seller) { create(:user) }
before do
routes.draw { get :action, to: "anonymous#action" }
cookies[:_gumroad_guid] = "abc123"
request.remote_ip = "192.168.0.1"
Feature.activate_user(:utm_links, seller)
end
context "when a matching UTM link is found" do
let!(:utm_link) { create(:utm_link, seller:) }
before do
request.host = "#{seller.subdomain}"
request.path = "/"
end
it "records UTM link visit", :sidekiq_inline do
expect do
expect do
get :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium, utm_campaign: utm_link.utm_campaign, utm_content: utm_link.utm_content, utm_term: utm_link.utm_term }
end.to change(UtmLinkVisit, :count).by(1)
end.not_to change(UtmLink, :count)
expect(utm_link.reload.total_clicks).to eq(1)
expect(utm_link.unique_clicks).to eq(1)
visit = utm_link.utm_link_visits.last
expect(visit.browser_guid).to eq("abc123")
expect(visit.ip_address).to eq("192.168.0.1")
expect(visit.country_code).to be_nil
expect(visit.referrer).to be_nil
expect(visit.user_agent).to eq("Rails Testing")
# Visit from the same browser is recorded but not counted as a unique one
expect do
get :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium, utm_campaign: utm_link.utm_campaign, utm_content: utm_link.utm_content, utm_term: utm_link.utm_term }
end.to change(UtmLinkVisit, :count).from(1).to(2)
expect(utm_link.reload.total_clicks).to eq(2)
expect(utm_link.unique_clicks).to eq(1)
# When the UTM params don't match, no visit is recorded
expect do
get :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium }
end.not_to change(UtmLinkVisit, :count)
expect(utm_link.reload.total_clicks).to eq(2)
expect(utm_link.unique_clicks).to eq(1)
end
it "enqueues a job to update the UTM link stats" do
get :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium, utm_campaign: utm_link.utm_campaign, utm_content: utm_link.utm_content, utm_term: utm_link.utm_term }
expect(UpdateUtmLinkStatsJob).to have_enqueued_sidekiq_job(utm_link.id)
end
it "does nothing for non-GET requests" do
expect do
post :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium, utm_campaign: utm_link.utm_campaign, utm_content: utm_link.utm_content, utm_term: utm_link.utm_term }
end.not_to change(UtmLinkVisit, :count)
expect(UpdateUtmLinkStatsJob).not_to have_enqueued_sidekiq_job(utm_link.id)
end
it "does not track UTM link visits when cookies are disabled" do
cookies[:_gumroad_guid] = nil
expect do
get :action, params: { utm_source: utm_link.utm_source, utm_medium: utm_link.utm_medium, utm_campaign: utm_link.utm_campaign, utm_content: utm_link.utm_content, utm_term: utm_link.utm_term }
end.not_to change(UtmLinkVisit, :count)
expect(response).to be_successful
expect(UpdateUtmLinkStatsJob).not_to have_enqueued_sidekiq_job(utm_link.id)
end
end
context "when a matching UTM link is not found" do
let(:product) { create(:product, user: seller) }
let(:post) { create(:published_installment, seller:, shown_on_profile: true) }
let(:utm_params) do
{
utm_source: "facebook",
utm_medium: "social",
utm_campaign: "summer_sale",
utm_content: "Banner 1",
utm_term: "discount"
}
end
before do
Feature.activate_user(:utm_links, seller)
request.host = "#{seller.subdomain}"
end
context "on a product page" do
before do
allow(controller).to receive(:short_link_path).and_return("/l/#{product.unique_permalink}")
request.path = "/l/#{product.unique_permalink}"
end
it "creates a new UTM link and records the visit", :sidekiq_inline do
expect do
get :action, params: utm_params.merge(id: product.unique_permalink)
end.to change(UtmLink, :count).by(1)
.and change(UtmLinkVisit, :count).by(1)
utm_link = UtmLink.last
expect(utm_link.seller).to eq(seller)
expect(utm_link.title).to eq("Product — #{product.name} (auto-generated)")
expect(utm_link.target_resource_type).to eq("product_page")
expect(utm_link.target_resource_id).to eq(product.id)
expect(utm_link.utm_source).to eq("facebook")
expect(utm_link.utm_medium).to eq("social")
expect(utm_link.utm_campaign).to eq("summer_sale")
expect(utm_link.utm_content).to eq("banner-1")
expect(utm_link.utm_term).to eq("discount")
expect(utm_link.ip_address).to eq("192.168.0.1")
expect(utm_link.browser_guid).to eq("abc123")
expect(utm_link.first_click_at).to be_present
expect(utm_link.last_click_at).to be_present
expect(utm_link.total_clicks).to eq(1)
expect(utm_link.unique_clicks).to eq(1)
visit = utm_link.utm_link_visits.last
expect(visit.browser_guid).to eq("abc123")
expect(visit.ip_address).to eq("192.168.0.1")
expect(visit.country_code).to be_nil
expect(visit.referrer).to be_nil
expect(visit.user_agent).to eq("Rails Testing")
# Another visit from the same browser does not create a new UTM link, but does record a visit
expect do
get :action, params: utm_params.merge(id: product.unique_permalink)
end.to change(UtmLink, :count).by(0)
.and change(UtmLinkVisit, :count).by(1)
expect(utm_link.reload.total_clicks).to eq(2)
expect(utm_link.unique_clicks).to eq(1)
end
end
context "on a post page" do
before do
allow(Iffy::Post::IngestJob).to receive(:perform_async)
allow(controller).to receive(:custom_domain_view_post_path).and_return("/posts/#{post.slug}")
request.host = "#{seller.subdomain}"
request.path = "/posts/#{post.slug}"
end
it "creates a new UTM link and records the visit", :sidekiq_inline do
expect do
get :action, params: utm_params.merge(slug: post.slug)
end.to change(UtmLink, :count).by(1)
.and change(UtmLinkVisit, :count).by(1)
utm_link = UtmLink.last
expect(utm_link.seller).to eq(seller)
expect(utm_link.title).to eq("Post — #{post.name} (auto-generated)")
expect(utm_link.target_resource_type).to eq("post_page")
expect(utm_link.target_resource_id).to eq(post.id)
expect(utm_link.utm_source).to eq("facebook")
expect(utm_link.utm_medium).to eq("social")
expect(utm_link.utm_campaign).to eq("summer_sale")
expect(utm_link.utm_content).to eq("banner-1")
expect(utm_link.utm_term).to eq("discount")
expect(utm_link.ip_address).to eq("192.168.0.1")
expect(utm_link.browser_guid).to eq("abc123")
expect(utm_link.first_click_at).to be_present
expect(utm_link.last_click_at).to be_present
expect(utm_link.total_clicks).to eq(1)
expect(utm_link.unique_clicks).to eq(1)
visit = utm_link.utm_link_visits.last
expect(visit.browser_guid).to eq("abc123")
expect(visit.ip_address).to eq("192.168.0.1")
expect(visit.country_code).to be_nil
expect(visit.referrer).to be_nil
expect(visit.user_agent).to eq("Rails Testing")
# Another visit from the same browser does not create a new UTM link, but does record a visit
expect do
get :action, params: utm_params.merge(slug: post.slug)
end.to change(UtmLink, :count).by(0)
.and change(UtmLinkVisit, :count).by(1)
expect(utm_link.reload.total_clicks).to eq(2)
expect(utm_link.unique_clicks).to eq(1)
end
end
context "on the profile page" do
before do
allow(controller).to receive(:root_path).and_return("/")
request.host = "#{seller.subdomain}"
request.path = "/"
end
it "creates a new UTM link and records the visit", :sidekiq_inline do
expect do
get :action, params: utm_params
end.to change(UtmLink, :count).by(1)
.and change(UtmLinkVisit, :count).by(1)
utm_link = UtmLink.last
expect(utm_link.seller).to eq(seller)
expect(utm_link.target_resource_type).to eq("profile_page")
expect(utm_link.target_resource_id).to be_nil
expect(utm_link.title).to eq("Profile page (auto-generated)")
expect(utm_link.utm_source).to eq("facebook")
expect(utm_link.utm_medium).to eq("social")
expect(utm_link.utm_campaign).to eq("summer_sale")
expect(utm_link.utm_content).to eq("banner-1")
expect(utm_link.utm_term).to eq("discount")
expect(utm_link.ip_address).to eq("192.168.0.1")
expect(utm_link.browser_guid).to eq("abc123")
expect(utm_link.first_click_at).to be_present
expect(utm_link.last_click_at).to be_present
expect(utm_link.total_clicks).to eq(1)
expect(utm_link.unique_clicks).to eq(1)
visit = utm_link.utm_link_visits.last
expect(visit.browser_guid).to eq("abc123")
expect(visit.ip_address).to eq("192.168.0.1")
expect(visit.country_code).to be_nil
expect(visit.referrer).to be_nil
expect(visit.user_agent).to eq("Rails Testing")
# Another visit from the same browser does not create a new UTM link, but does record a visit
expect do
get :action, params: utm_params
end.to change(UtmLink, :count).by(0)
.and change(UtmLinkVisit, :count).by(1)
end
end
context "on the subscribe page" do
before do
allow(controller).to receive(:custom_domain_subscribe_path).and_return("/subscribe")
request.host = "#{seller.subdomain}"
request.path = "/subscribe"
end
it "creates a new UTM link and records the visit", :sidekiq_inline do
expect do
get :action, params: utm_params
end.to change(UtmLink, :count).by(1)
.and change(UtmLinkVisit, :count).by(1)
utm_link = UtmLink.last
expect(utm_link.seller).to eq(seller)
expect(utm_link.target_resource_type).to eq("subscribe_page")
expect(utm_link.target_resource_id).to be_nil
expect(utm_link.title).to eq("Subscribe page (auto-generated)")
expect(utm_link.utm_source).to eq("facebook")
expect(utm_link.utm_medium).to eq("social")
expect(utm_link.utm_campaign).to eq("summer_sale")
expect(utm_link.utm_content).to eq("banner-1")
expect(utm_link.utm_term).to eq("discount")
expect(utm_link.ip_address).to eq("192.168.0.1")
expect(utm_link.browser_guid).to eq("abc123")
expect(utm_link.first_click_at).to be_present
expect(utm_link.last_click_at).to be_present
expect(utm_link.total_clicks).to eq(1)
expect(utm_link.unique_clicks).to eq(1)
visit = utm_link.utm_link_visits.last
expect(visit.browser_guid).to eq("abc123")
expect(visit.ip_address).to eq("192.168.0.1")
expect(visit.country_code).to be_nil
expect(visit.referrer).to be_nil
expect(visit.user_agent).to eq("Rails Testing")
# Another visit from the same browser does not create a new UTM link, but does record a visit
expect do
get :action, params: utm_params
end.to change(UtmLink, :count).by(0)
.and change(UtmLinkVisit, :count).by(1)
end
end
it "does not auto-create UTM link when feature is disabled" do
Feature.deactivate_user(:utm_links, seller)
request.host = "#{seller.subdomain}"
request.path = "/"
expect do
expect do
get :action, params: utm_params
end.not_to change(UtmLink, :count)
end.not_to change(UtmLinkVisit, :count)
end
it "does not auto-create UTM link when cookies are disabled" do
cookies[:_gumroad_guid] = nil
request.host = "#{seller.subdomain}"
request.path = "/"
expect do
expect do
get :action, params: utm_params
end.not_to change(UtmLink, :count)
end.not_to change(UtmLinkVisit, :count)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/helper_widget_spec.rb | spec/controllers/concerns/helper_widget_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HelperWidget, type: :controller do
controller(ApplicationController) do
include HelperWidget
def action
head :ok
end
end
let(:seller) { create(:named_seller, email: "test@example.com") }
let(:user) { create(:user) }
before do
routes.draw { get ":action", controller: "anonymous" }
allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_SECRET").and_return("test_secret")
end
describe "#helper_widget_host" do
it "returns nil when config is not set" do
allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_HOST").and_return(nil)
expect(controller.helper_widget_host).to be_nil
end
it "returns the config value when set" do
allow(GlobalConfig).to receive(:get).with("HELPER_WIDGET_HOST").and_return("https://custom.helper.ai")
expect(controller.helper_widget_host).to eq("https://custom.helper.ai")
end
end
describe "#helper_session" do
it "returns nil when no seller is signed in" do
expect(controller.helper_session).to be_nil
end
it "returns email, emailHash and timestamp when signed in" do
sign_in(seller)
fixed_time = Time.zone.parse("2024-01-01 00:00:00 UTC")
allow(Time).to receive(:current).and_return(fixed_time)
timestamp_ms = (fixed_time.to_f * 1000).to_i
expected_hmac = OpenSSL::HMAC.hexdigest("sha256", "test_secret", "#{seller.email}:#{timestamp_ms}")
session = controller.helper_session
expect(session[:email]).to eq(seller.email)
expect(session[:emailHash]).to eq(expected_hmac)
expect(session[:timestamp]).to eq(timestamp_ms)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/custom_domain_route_builder_spec.rb | spec/controllers/concerns/custom_domain_route_builder_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CustomDomainRouteBuilder, type: :controller do
controller(ApplicationController) do
include CustomDomainRouteBuilder
def action
head :ok
end
end
before do
routes.draw { get :action, to: "anonymous#action" }
end
let!(:custom_domain) { "store.example1.com" }
describe "#build_view_post_route" do
let!(:post) { create(:installment) }
let!(:purchase) { create(:purchase) }
it "returns the correct URL for requests from a custom domain" do
@request.host = custom_domain
get :action
result = controller.build_view_post_route(post:, purchase_id: purchase.external_id)
expect(result).to eq(custom_domain_view_post_path(slug: post.slug, purchase_id: purchase.external_id))
end
it "returns the correct URL for requests from a non-custom domain" do
get :action
result = controller.build_view_post_route(post:, purchase_id: purchase.external_id)
expect(result).to eq(view_post_path(
username: post.user.username,
slug: post.slug,
purchase_id: purchase.external_id))
end
end
describe "#seller_custom_domain_url" do
let!(:user) { create(:user, username: "example") }
context "when the request is through a custom domain" do
before do
@request.host = custom_domain
end
it "returns root path" do
get :action
expect(controller.seller_custom_domain_url).to eq "http://#{custom_domain}/"
end
end
context "when the request is through a product custom domain" do
before do
create(:custom_domain, domain: custom_domain, product: create(:product))
@request.host = custom_domain
end
it "returns nil" do
get :action
expect(controller.seller_custom_domain_url).to be_nil
end
end
context "when the request is from a product custom domain page and there is an older dead matching domain" do
before do
create(:custom_domain, domain: custom_domain, deleted_at: DateTime.parse("2020-01-01"))
create(:custom_domain, :with_product, domain: custom_domain)
@request.host = custom_domain
end
it "returns nil" do
get :action
expect(controller.seller_custom_domain_url).to be_nil
end
end
context "when the request is not through a custom domain" do
it "returns nil" do
get :action
expect(controller.seller_custom_domain_url).to be_nil
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/concerns/current_seller_spec.rb | spec/controllers/concerns/current_seller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe CurrentSeller, type: :controller do
controller(ApplicationController) do
include CurrentSeller
before_action :authenticate_user!
def action
head :ok
end
end
before do
routes.draw { get :action, to: "anonymous#action" }
end
let(:seller) { create(:named_seller) }
let(:other_seller) { create(:user) }
shared_examples_for "invalid cookie" do
it "deletes cookie and assigns seller as current_seller" do
get :action
expect(controller.current_seller).to eq(seller)
expect(cookies.encrypted[:current_seller_id]).to eq(nil)
end
end
context "with seller signed in" do
before do
sign_in(seller)
end
context "when cookie is set" do
context "with correct value" do
before do
cookies.encrypted[:current_seller_id] = seller.id
end
it "keeps cookie and assigns seller as current_seller" do
get :action
expect(controller.current_seller).to eq(seller)
expect(cookies.encrypted[:current_seller_id]). to eq(seller.id)
end
end
context "with incorrect value" do
context "when cookie uses other seller that is not alive" do
before do
other_seller.update!(deleted_at: Time.current)
cookies.encrypted[:current_seller_id] = other_seller.id
end
it_behaves_like "invalid cookie"
end
context "when cookie uses an invalid value" do
before do
cookies.encrypted[:current_seller_id] = "foo"
end
it_behaves_like "invalid cookie"
end
context "when cookie uses another valid seller that is not a member of" do
before do
cookies.encrypted[:current_seller_id] = other_seller.id
end
it_behaves_like "invalid cookie"
end
end
end
context "when cookie is not set" do
it "assigns seller as current_seller" do
get :action
expect(controller.current_seller).to eq(seller)
expect(cookies.encrypted[:current_seller_id]).to eq(nil)
end
end
end
context "without seller signed in" do
context "when cookie is set" do
before do
cookies.encrypted[:current_seller_id] = seller.id
end
it "doesn't assign current_seller and don't destroy the cookie" do
get :action
expect(controller.current_seller).to eq(nil)
expect(cookies.encrypted[:current_seller_id]). to eq(seller.id)
end
end
context "when cookie is not set" do
it "doesn't assign current_seller and cookie" do
get :action
expect(controller.current_seller).to eq(nil)
expect(cookies.encrypted[:current_seller_id]).to eq(nil)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/workflows/emails_controller_spec.rb | spec/controllers/workflows/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 Workflows::EmailsController, 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 }
let(:request_params) { { workflow_id: workflow.external_id } }
end
it "renders successfully with Inertia" do
get :index, params: { workflow_id: workflow.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Workflows/Emails/Index")
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 :index, params: { workflow_id: "nonexistent" } }.to raise_error(ActionController::RoutingError)
end
end
end
describe "PATCH update" do
it_behaves_like "authorize called for action", :patch, :update do
let(:record) { workflow }
let(:request_params) { { workflow_id: workflow.external_id, workflow: { send_to_past_customers: true, save_action_name: "save", installments: [] } } }
end
it "303 redirects to emails page with a success message" do
installment_params = [{
id: "test-id",
name: "Test Email",
message: "<p>Test message</p>",
time_period: "hour",
time_duration: 1,
send_preview_email: false,
files: []
}]
patch :update, params: {
workflow_id: workflow.external_id,
workflow: {
send_to_past_customers: true,
save_action_name: "save",
installments: installment_params
}
}
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq(Workflows::EmailsController::FLASH_CHANGES_SAVED)
end
it "redirects with published message when save_action_name is save_and_publish" do
allow_any_instance_of(Workflow::SaveInstallmentsService).to receive(:process).and_return([true, nil])
patch :update, params: {
workflow_id: workflow.external_id,
workflow: {
send_to_past_customers: true,
save_action_name: "save_and_publish",
installments: []
}
}
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq(Workflows::EmailsController::FLASH_WORKFLOW_PUBLISHED)
end
it "redirects with unpublished message when save_action_name is save_and_unpublish" do
allow_any_instance_of(Workflow::SaveInstallmentsService).to receive(:process).and_return([true, nil])
patch :update, params: {
workflow_id: workflow.external_id,
workflow: {
send_to_past_customers: true,
save_action_name: "save_and_unpublish",
installments: []
}
}
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq(Workflows::EmailsController::FLASH_WORKFLOW_UNPUBLISHED)
end
context "when save fails" do
let(:errors) { workflow.errors.tap { |e| e.add(:base, "Installment message is required") } }
before do
allow_any_instance_of(Workflow::SaveInstallmentsService).to receive(:process).and_return([false, errors])
end
it "redirects with Inertia errors and specific alert message" do
patch :update, params: {
workflow_id: workflow.external_id,
workflow: {
send_to_past_customers: true,
save_action_name: "save",
installments: []
}
}
expect(response).to redirect_to(workflow_emails_path(workflow.external_id))
expect(flash[:alert]).to eq("Installment message is required")
expect(session[:inertia_errors]).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/payouts/exportables_controller_spec.rb | spec/controllers/payouts/exportables_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe Payouts::ExportablesController, type: :controller do
let(:seller) { create(:named_seller) }
before do
sign_in seller
end
describe "GET #index" do
context "when the seller has payouts" do
let!(:payouts_2021) { create_list(:payment_completed, 2, user: seller, created_at: Time.zone.local(2021, 1, 1)) }
let!(:payouts_2022) { create_list(:payment_completed, 3, user: seller, created_at: Time.zone.local(2022, 1, 1)) }
it "returns data with the most recent year if no year is provided" do
get :index
expect(response.parsed_body["years_with_payouts"]).to contain_exactly(2021, 2022)
expect(response.parsed_body["selected_year"]).to eq(2022)
expect(response.parsed_body["payouts_in_selected_year"]).to contain_exactly(
{
id: payouts_2022.first.external_id,
date_formatted: "January 1st, 2022"
},
{
id: payouts_2022.second.external_id,
date_formatted: "January 1st, 2022"
},
{
id: payouts_2022.third.external_id,
date_formatted: "January 1st, 2022"
}
)
end
it "returns data with the most recent year if user does not have payouts in the selected year" do
get :index, params: { year: 2025 }
expect(response.parsed_body["years_with_payouts"]).to contain_exactly(2021, 2022)
expect(response.parsed_body["selected_year"]).to eq(2022)
expect(response.parsed_body["payouts_in_selected_year"]).to contain_exactly(
{
id: payouts_2022.first.external_id,
date_formatted: "January 1st, 2022"
},
{
id: payouts_2022.second.external_id,
date_formatted: "January 1st, 2022"
},
{
id: payouts_2022.third.external_id,
date_formatted: "January 1st, 2022"
}
)
end
it "returns payouts for the selected year" do
get :index, params: { year: 2021 }
expect(response.parsed_body["selected_year"]).to eq(2021)
expect(response.parsed_body["payouts_in_selected_year"].length).to eq(2)
expect(response.parsed_body["payouts_in_selected_year"]).to contain_exactly(
{
id: payouts_2021.first.external_id,
date_formatted: "January 1st, 2021"
},
{
id: payouts_2021.second.external_id,
date_formatted: "January 1st, 2021"
}
)
end
end
context "when the seller has no payouts" do
it "populates the year-related attributes with the current year" do
current_year = Time.zone.now.year
get :index
expect(response.parsed_body["years_with_payouts"]).to contain_exactly(current_year)
expect(response.parsed_body["selected_year"]).to eq(current_year)
expect(response.parsed_body["payouts_in_selected_year"]).to eq([])
end
end
context "when there are payments that are not completed or not displayable" do
before do
# Create completed payments that should be included
create_list(:payment_completed, 2, user: seller, created_at: Time.zone.local(2022, 1, 1))
# Create payments with other states that should be excluded
create(:payment, user: seller, state: "processing", created_at: Time.zone.local(2022, 2, 1))
create(:payment, user: seller, state: "failed", created_at: Time.zone.local(2022, 3, 1))
# Create a payment before the OLDEST_DISPLAYABLE_PAYOUT_PERIOD_END_DATE
too_old_to_display = PayoutsHelper::OLDEST_DISPLAYABLE_PAYOUT_PERIOD_END_DATE - 1.year
create(:payment_completed, user: seller, created_at: too_old_to_display)
end
it "only returns data that are both completed and displayable" do
get :index
expect(response.parsed_body["years_with_payouts"]).to contain_exactly(2022)
expect(response.parsed_body["selected_year"]).to eq(2022)
expect(response.parsed_body["payouts_in_selected_year"].length).to eq(2)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/payouts/exports_controller_spec.rb | spec/controllers/payouts/exports_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
RSpec.describe Payouts::ExportsController, type: :controller do
let(:seller) { create(:named_seller) }
before do
sign_in seller
end
describe "POST #create" do
context "when no parameters are provided" do
it "returns unprocessable entity" do
post :create, format: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)["error"]).to eq("Invalid payouts")
end
end
context "when invalid parameters are provided" do
it "returns unprocessable entity" do
post :create, params: { payment_ids: ["invalid_id"] }, format: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)["error"]).to eq("Invalid payouts")
post :create, params: { payment_ids: [] }, format: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)["error"]).to eq("Invalid payouts")
post :create, params: { payment_ids: "invalid_id" }, format: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)["error"]).to eq("Invalid payouts")
end
end
context "when valid parameters are provided" do
let!(:payouts) { create_list(:payment_completed, 2, user: seller) }
it "queues a job with the expected parameters" do
expect do
post :create, params: { payout_ids: payouts.map(&:external_id) }, format: :json
end.to change(ExportPayoutData.jobs, :size).by(1)
expect(response).to have_http_status(:ok)
job = ExportPayoutData.jobs.last
expect(job["args"][0]).to match_array(payouts.map(&:id))
expect(job["args"][1]).to eq(seller.id)
end
end
context "when a payout ID for a different seller is provided" do
let(:other_seller) { create(:user) }
let(:other_seller_payout) { create(:payment_completed, user: other_seller) }
it "fails with unprocessable entity" do
expect do
post :create, params: { payout_ids: [other_seller_payout.external_id] }, format: :json
end.not_to change(ExportPayoutData.jobs, :size)
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)["error"]).to eq("Invalid payouts")
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/onboarding_form_controller_spec.rb | spec/controllers/affiliate_requests/onboarding_form_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/sellers_base_controller_concern"
describe AffiliateRequests::OnboardingFormController do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
let(:published_product_one) { create(:product, user: seller) }
let(:published_product_two) { create(:product, user: seller) }
let!(:published_product_three) { create(:product, user: seller) }
let(:unpublished_product) { create(:product, user: seller, purchase_disabled_at: DateTime.current) }
let!(:published_collab_product) { create(:product, :is_collab, user: seller) }
let!(:deleted_product) { create(:product, user: seller, deleted_at: DateTime.current) }
let!(:enabled_self_service_affiliate_product_for_published_product_one) { create(:self_service_affiliate_product, enabled: true, seller:, product: published_product_one, affiliate_basis_points: 1000) }
let!(:enabled_self_service_affiliate_product_for_published_product_two) { create(:self_service_affiliate_product, enabled: true, seller:, product: published_product_two, destination_url: "https://example.com") }
let!(:enabled_self_service_affiliate_product_for_collab_product) do
create(:self_service_affiliate_product, enabled: true, seller:).tap do
_1.product.update!(is_collab: true) # bypass `product_is_not_a_collab` validation
end
end
let(:self_service_collab_product) { enabled_self_service_affiliate_product_for_collab_product.product }
include_context "with user signed in as admin for seller"
describe "PATCH update" do
it_behaves_like "authorize called for action", :patch, :update do
let(:record) { :onboarding_form }
let(:policy_klass) { AffiliateRequests::OnboardingFormPolicy }
end
context "when the request payload contains invalid information" do
context "such as an invalid fee percent" do
let(:params) do
{
products: [
{ id: published_product_one.external_id_numeric, enabled: true, name: published_product_one.name, fee_percent: 500, destination_url: nil }
]
}
end
it "responds with an error without persisting any changes" do
expect do
patch :update, params:, format: :json
end.to_not change { seller.self_service_affiliate_products.reload }
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Validation failed: Affiliate commission must be between 1% and 75%."
end
end
context "such as an ineligible product" do
let(:params) do
{
products: [
{ id: published_collab_product.external_id_numeric, enabled: true, name: published_collab_product.name, fee_percent: 40, destination_url: nil }
]
}
end
it "responds with an error without persisting any changes" do
expect do
patch :update, params:, format: :json
end.to_not change { seller.self_service_affiliate_products.reload }
expect(response.parsed_body["success"]).to eq false
expect(response.parsed_body["error"]).to eq "Validation failed: Collab products cannot have affiliates"
end
end
end
context "when the request payload is valid" do
let(:params) do
{
products: [
{ id: published_product_one.external_id_numeric, enabled: false, name: published_product_one.name, fee_percent: 10, destination_url: nil },
{ id: published_product_two.external_id_numeric, enabled: false, fee_percent: 5, destination_url: "https://example.com" },
{ id: published_product_three.external_id_numeric, enabled: true, name: published_product_three.name, fee_percent: 25, destination_url: "https://example.com/test" },
{ id: self_service_collab_product.external_id_numeric, enabled: false, name: self_service_collab_product.name, fee_percent: 10 },
{ id: "12345", enabled: true, name: "A product", fee_percent: 10, destination_url: nil }
],
disable_global_affiliate: true
}
end
it "upserts the self service affiliate products, ignoring ineligible products and updates the global affiliate status" do
expect do
patch :update, params:, format: :json
seller.reload
end.to change { seller.self_service_affiliate_products.count }.from(3).to(4)
.and change { seller.self_service_affiliate_products.enabled.count }.from(3).to(1)
.and change { seller.disable_global_affiliate }.from(false).to(true)
expect(response.parsed_body["success"]).to eq(true)
expect(enabled_self_service_affiliate_product_for_published_product_one.reload.enabled).to eq(false)
expect(enabled_self_service_affiliate_product_for_published_product_two.reload.enabled).to eq(false)
expect(enabled_self_service_affiliate_product_for_published_product_two.destination_url).to eq("https://example.com")
expect(enabled_self_service_affiliate_product_for_collab_product.reload.enabled).to eq(false)
expect(seller.self_service_affiliate_products.last.slice(:product_id, :affiliate_basis_points, :destination_url)).to eq(
"product_id" => published_product_three.id,
"affiliate_basis_points" => 2500,
"destination_url" => "https://example.com/test"
)
end
context "when a pending affiliate request exists and all products are being disabled" do
let!(:pending_affiliate_request) { create(:affiliate_request, seller:) }
let(:params) do
{
products: [
{ id: published_product_one.external_id_numeric, enabled: false, fee_percent: 10 },
{ id: published_product_two.external_id_numeric, enabled: false, fee_percent: 5 },
{ id: published_product_three.external_id_numeric, enabled: false, fee_percent: 25 },
{ id: "12345", enabled: true, fee_percent: 10 }
]
}
end
it "responds with an error and does not persist the requested changes" do
expect do
expect do
patch :update, params:, as: :json
end.to_not change { seller.self_service_affiliate_products.count }
end.to_not change { seller.self_service_affiliate_products.enabled.count }
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error"]).to eq("You need to have at least one product enabled since there are some pending affiliate requests")
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/purchases/pings_controller_spec.rb | spec/controllers/purchases/pings_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/sellers_base_controller_concern"
describe Purchases::PingsController do
it_behaves_like "inherits from Sellers::BaseController"
render_views
describe "POST create" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:purchase) { create(:purchase, link: product, seller:) }
context "when making a request while unauthenticated" do
it "does not allow resending the ping" do
expect_any_instance_of(Purchase).to_not receive(:send_notification_webhook_from_ui)
post :create, format: :json, params: { purchase_id: purchase.external_id }
expect(response).to have_http_status(:not_found)
end
end
context "when making a request while authenticated" do
context "when signed in as a user other than the seller of the purchase for which a ping is to be resent" do
it "does not allow resending the ping" do
expect_any_instance_of(Purchase).to_not receive(:send_notification_webhook_from_ui)
sign_in(create(:user))
post :create, format: :json, params: { purchase_id: purchase.external_id }
expect(response).to have_http_status(:not_found)
end
end
context "when signed in as the seller of the purchase for which a ping is to be resent" do
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for action", :post, :create do
let(:record) { purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:policy_method) { :create_ping? }
let(:request_params) { { purchase_id: purchase.external_id } }
end
it "resends the ping and responds with success" do
expect_any_instance_of(Purchase).to(
receive(:send_notification_webhook_from_ui).and_call_original)
post :create, format: :json, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
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/purchases/dispute_evidence_controller_spec.rb | spec/controllers/purchases/dispute_evidence_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
describe Purchases::DisputeEvidenceController do
let(:dispute_evidence) { create(:dispute_evidence) }
let(:purchase) { dispute_evidence.disputable.purchase_for_dispute_evidence }
describe "GET show" do
context "when the seller hasn't been contacted" do
before do
dispute_evidence.update_as_not_seller_contacted!
end
it "redirects" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("You are not allowed to perform this action.")
end
end
context "when the seller has already submitted" do
before do
dispute_evidence.update_as_seller_submitted!
end
it "redirects" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Additional information has already been submitted for this dispute.")
end
end
context "when the dispute has already been submitted" do
before do
dispute_evidence.update_as_resolved!(resolution: DisputeEvidence::RESOLUTION_SUBMITTED)
end
it "redirects" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Additional information can no longer be submitted for this dispute.")
end
end
RSpec.shared_examples "shows the dispute evidence page for the purchase" do
it "shows the dispute evidence page for the purchase" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
expect(assigns[:title]).to eq("Submit additional information")
expect(assigns[:hide_layouts]).to be(true)
expect(assigns[:dispute_evidence]).to eq(dispute_evidence)
expect(assigns[:purchase]).to eq(purchase)
dispute_evidence_page_presenter = assigns(:dispute_evidence_page_presenter)
expect(dispute_evidence_page_presenter.send(:purchase)).to eq(purchase)
end
end
context "when the dispute belongs to a charge" do
let!(:charge) do
charge = create(:charge)
charge.purchases << create(:purchase)
charge.purchases << create(:purchase)
charge
end
let!(:purchase) { charge.purchase_for_dispute_evidence }
let!(:dispute_evidence) do
dispute = create(:dispute, purchase: nil, charge:)
create(:dispute_evidence_on_charge, dispute:)
end
it_behaves_like "shows the dispute evidence page for the purchase"
end
it "404s for an invalid purchase id" do
expect do
get :show, params: { purchase_id: "1234" }
end.to raise_error(ActionController::RoutingError)
end
it "adds X-Robots-Tag response header to avoid page indexing" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
expect(response.headers["X-Robots-Tag"]).to eq("noindex")
end
end
describe "PUT update" do
it "updates the dispute evidence" do
put :update, params: {
purchase_id: purchase.external_id,
dispute_evidence: {
reason_for_winning: "Reason for winning",
cancellation_rebuttal: "Cancellation rebuttal",
refund_refusal_explanation: "Refusal explanation"
}
}
dispute_evidence = assigns(:dispute_evidence)
expect(dispute_evidence.reason_for_winning).to eq("Reason for winning")
expect(dispute_evidence.cancellation_rebuttal).to eq("Cancellation rebuttal")
expect(dispute_evidence.refund_refusal_explanation).to eq("Refusal explanation")
expect(dispute_evidence.seller_submitted?).to be(true)
expect(response.parsed_body).to eq({ "success" => true })
end
context "when a signed_id for a PNG file is provided" do
let(:blob) do
ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("smilie.png"), filename: "receipt_image.png", content_type: "image/png")
end
it "converts the file to JPG and attaches it to the dispute evidence" do
# Purging in test ENV returns Aws::S3::Errors::AccessDenied
allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil)
put :update, params: { purchase_id: purchase.external_id, dispute_evidence: { customer_communication_file_signed_blob_id: blob.signed_id } }
dispute_evidence = assigns(:dispute_evidence)
expect(dispute_evidence.customer_communication_file.attached?).to be(true)
expect(dispute_evidence.customer_communication_file.filename.to_s).to eq("receipt_image.jpg")
expect(dispute_evidence.customer_communication_file.content_type).to eq("image/jpeg")
expect(response.parsed_body).to eq({ "success" => true })
end
end
context "when a signed_id for a PDF file is provided" do
let(:blob) do
ActiveStorage::Blob.create_and_upload!(io: fixture_file_upload("test.pdf"), filename: "test.pdf", content_type: "application/pdf")
end
it "attaches it to the dispute evidence" do
put :update, params: { purchase_id: purchase.external_id, dispute_evidence: { customer_communication_file_signed_blob_id: blob.signed_id } }
dispute_evidence = assigns(:dispute_evidence)
expect(dispute_evidence.customer_communication_file.attached?).to be(true)
expect(dispute_evidence.customer_communication_file.filename.to_s).to eq("test.pdf")
expect(dispute_evidence.customer_communication_file.content_type).to eq("application/pdf")
expect(response.parsed_body).to eq({ "success" => true })
end
end
context "when the dispute evidence is invalid" do
it "returns errors" do
put :update, params: { purchase_id: purchase.external_id, dispute_evidence: { cancellation_rebuttal: "a" * 3_001 } }
dispute_evidence = assigns(:dispute_evidence)
expect(dispute_evidence.valid?).to be(false)
expect(response.parsed_body).to eq({ "success" => false, "error" => "Cancellation rebuttal is too long (maximum is 3000 characters)" })
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/purchases/variants_controller_spec.rb | spec/controllers/purchases/variants_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
require "shared_examples/authorize_called"
require "shared_examples/sellers_base_controller_concern"
describe Purchases::VariantsController do
it_behaves_like "inherits from Sellers::BaseController"
describe "PUT update" do
let(:seller) { create(:named_seller) }
let(:product) { create(:product, user: seller) }
let(:category) { create(:variant_category, link: product, title: "Color") }
let(:blue_variant) { create(:variant, variant_category: category, name: "Blue") }
let(:green_variant) { create(:variant, variant_category: category, name: "Green") }
let(:purchase) { create(:purchase, link: product, variant_attributes: [blue_variant]) }
context "authenticated as a different user" do
it "returns a 404" do
user = create(:user)
product = create(:product)
category = create(:variant_category, link: product, title: "Color")
blue_variant = create(:variant, variant_category: category, name: "Blue")
purchase = create(:purchase, link: product)
sign_in user
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: blue_variant.external_id, quantity: purchase.quantity }
expect(response).to have_http_status :not_found
expect(response.parsed_body).to eq(
"success" => false,
"error" => "Not found"
)
end
end
context "unauthenticated" do
it "returns a 404" do
product = create(:product)
category = create(:variant_category, link: product, title: "Color")
blue_variant = create(:variant, variant_category: category, name: "Blue")
purchase = create(:purchase, link: product)
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: blue_variant.external_id, quantity: purchase.quantity }
expect(response).to have_http_status :not_found
expect(response.parsed_body).to eq(
"success" => false,
"error" => "Not found"
)
end
end
context "with user signed in as admin for seller" do
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for action", :put, :update do
let(:record) { purchase }
let(:policy_klass) { Audience::PurchasePolicy }
let(:request_params) { { purchase_id: purchase.external_id, variant_id: green_variant.external_id } }
end
it "updates the variant for the given category" do
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: green_variant.external_id, quantity: purchase.quantity + 1 }
expect(response).to be_successful
purchase.reload
expect(purchase.variant_attributes).to eq [green_variant]
expect(purchase.quantity).to eq 2
end
context "for a product with SKUs" do
it "updates the SKU" do
product = create(:physical_product, user: seller)
create(:variant_category, link: product, title: "Color")
create(:variant_category, link: product, title: "Size")
large_blue_sku = create(:sku, link: product, name: "Blue - large")
small_green_sku = create(:sku, link: product, name: "Green - small")
purchase = create(:physical_purchase, link: product, variant_attributes: [large_blue_sku])
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: small_green_sku.external_id, quantity: purchase.quantity }
expect(response).to be_successful
expect(purchase.reload.variant_attributes).to eq [small_green_sku]
end
end
context "for a product without an associated variant" do
let(:purchase) { create(:purchase, link: product) }
it "adds the variant" do
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: green_variant.external_id, quantity: purchase.quantity }
expect(response).to be_successful
expect(purchase.reload.variant_attributes).to eq [green_variant]
end
end
context "when the new variant has insufficient inventory" do
let(:blue_variant) { create(:variant, variant_category: category, name: "Blue", max_purchase_count: 2) }
let(:purchase) { create(:purchase, link: product, variant_attributes: [green_variant]) }
it "returns an unsuccessful response" do
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: blue_variant.external_id, quantity: 3 }
expect(response).to_not be_successful
purchase.reload
expect(purchase.variant_attributes).to eq [green_variant]
expect(purchase.quantity).to eq 1
end
end
context "with an invalid variant ID" do
it "returns an unsuccessful response" do
purchase = create(:purchase, link: product)
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: "fake-id-123", quantity: purchase.quantity }
expect(response).to_not be_successful
end
end
context "when the existing variant has insuffient inventory" do
it "returns an unsuccessful response" do
purchase = create(:purchase, link: product)
green_variant.update!(max_purchase_count: 1)
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: green_variant.external_id, quantity: purchase.quantity + 1 }
expect(response).to_not be_successful
expect(purchase.reload.quantity).to eq 1
end
end
end
end
context "authenticated as a different user" do
it "returns a 404" do
user = create(:user)
product = create(:product)
category = create(:variant_category, link: product, title: "Color")
blue_variant = create(:variant, variant_category: category, name: "Blue")
purchase = create(:purchase, link: product)
sign_in user
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: blue_variant.external_id, quantity: purchase.quantity }
expect(response).to_not be_successful
expect(response).to have_http_status :not_found
end
end
context "unauthenticated" do
it "returns a 404" do
product = create(:product)
category = create(:variant_category, link: product, title: "Color")
blue_variant = create(:variant, variant_category: category, name: "Blue")
purchase = create(:purchase, link: product)
put :update, format: :json, params: { purchase_id: purchase.external_id, variant_id: blue_variant.external_id, quantity: purchase.quantity }
expect(response).to_not be_successful
expect(response).to have_http_status :not_found
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/product_controller_spec.rb | spec/controllers/purchases/product_controller_spec.rb | # frozen_string_literal: false
require "spec_helper"
describe Purchases::ProductController do
let(:purchase) { create(:purchase) }
describe "GET show" do
it "shows the product for the purchase" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
purchase_product_presenter = assigns(:purchase_product_presenter)
expect(purchase_product_presenter.product).to eq(purchase.link)
product_props = assigns(:product_props)
expect(product_props).to eq(ProductPresenter.new(product: purchase.link, request:).product_props(seller_custom_domain_url: nil).deep_merge(purchase_product_presenter.product_props))
end
it "404s for an invalid purchase id" do
expect do
get :show, params: { purchase_id: "1234" }
end.to raise_error(ActionController::RoutingError)
end
it "adds X-Robots-Tag response header to avoid page indexing" do
get :show, params: { purchase_id: purchase.external_id }
expect(response).to be_successful
expect(response.headers["X-Robots-Tag"]).to eq("noindex")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/integrations/discord_controller_spec.rb | spec/controllers/integrations/discord_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Integrations::DiscordController do
before do
sign_in create(:user)
end
let(:oauth_request_body) do
{
grant_type: "authorization_code",
code: "test_code",
client_id: DISCORD_CLIENT_ID,
client_secret: DISCORD_CLIENT_SECRET,
redirect_uri: oauth_redirect_integrations_discord_index_url
}
end
let(:oauth_request_header) { { "Content-Type" => "application/x-www-form-urlencoded" } }
describe "GET server_info" do
it "returns server information for a valid oauth code" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token", guild: { id: "0", name: "Gaming" } }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot" }.to_json,
headers: { content_type: "application/json" })
get :server_info, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true,
"server_id" => "0",
"server_name" => "Gaming",
"username" => "gumbot" })
end
it "fails if oauth authorization fails" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 500)
get :server_info, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have access token" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { guild: { id: "0", name: "Gaming" } }.to_json,
headers: { content_type: "application/json" })
get :server_info, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have guild information" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
get :server_info, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user identification fails" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token", guild: { id: "0", name: "Gaming" } }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 401, body: { code: Discordrb::Errors::Unauthorized.code }.to_json)
get :server_info, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET oauth_redirect" do
it "returns successful response if code is present" do
get :oauth_redirect, format: :json, params: { code: "test_code" }
expect(response.status).to eq(200)
end
it "fails if code is not present" do
get :oauth_redirect, format: :json
expect(response.status).to eq(400)
end
it "redirects to subdomain if specified in state" do
user = create(:user, username: "test")
get :oauth_redirect, format: :json, params: { code: "test_code", state: { seller_id: ObfuscateIds.encrypt(user.id), is_custom_domain: false }.to_json }
expect(response).to redirect_to(oauth_redirect_integrations_discord_index_url(host: user.subdomain, params: { code: "test_code" }))
end
it "redirects to custom domain if specified in state" do
user = create(:user, username: "test")
custom_domain = CustomDomain.create(user:, domain: "www.test-custom-domain.com")
get :oauth_redirect, format: :json, params: { code: "test_code", state: { seller_id: ObfuscateIds.encrypt(user.id), is_custom_domain: true }.to_json }
expect(response).to redirect_to(oauth_redirect_integrations_discord_index_url(host: custom_domain.domain, params: { code: "test_code" }))
end
end
describe "GET join_server" do
let(:user_id) { "user-0" }
let(:integration) { create(:discord_integration) }
let(:product) { create(:product, active_integrations: [integration]) }
let(:purchase) { create(:purchase, link: product) }
it "adds member to server for a purchase with an enabled integration and a valid code" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot", id: user_id }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 201)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(1)
purchase_discord_integration = PurchaseIntegration.last
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "server_name" => "Gaming" })
expect(purchase_discord_integration.purchase).to eq(purchase)
expect(purchase_discord_integration.integration).to eq(integration)
expect(purchase_discord_integration.discord_user_id).to eq(user_id)
end
it "adds member to server for a variant purchase with an enabled integration and a valid code" do
variant_category = create(:variant_category, link: product)
variant = create(:variant, variant_category:, active_integrations: [integration])
purchase = create(:purchase, link: product, variant_attributes: [variant])
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot", id: user_id }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 201)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(1)
purchase_discord_integration = PurchaseIntegration.last
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "server_name" => "Gaming" })
expect(purchase_discord_integration.purchase).to eq(purchase)
expect(purchase_discord_integration.integration).to eq(integration)
expect(purchase_discord_integration.discord_user_id).to eq(user_id)
end
it "fails if code is not passed" do
expect do
get :join_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if purchase_id is not passed" do
expect do
get :join_server, format: :json, params: { code: "test_code" }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization fails" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 500)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth response does not have access token" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200, headers: { content_type: "application/json" })
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user identification fails" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 401, body: { code: Discordrb::Errors::Unauthorized.code }.to_json)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if access_token is invalid" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot", id: user_id }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 403)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if purchased product does not have an integration" do
purchase = create(:purchase)
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot", id: user_id }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 403)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if purchase_integration record creation fails" do
WebMock.stub_request(:post, DISCORD_OAUTH_TOKEN_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: "test_access_token" }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{Discordrb::API.api_base}/users/@me").
with(headers: { "Authorization" => "Bearer test_access_token" }).
to_return(status: 200,
body: { username: "gumbot", id: user_id }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:put, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 403)
allow(PurchaseIntegration).to receive(:save).and_raise(ActiveRecord::ActiveRecordError)
expect do
get :join_server, format: :json, params: { code: "test_code", purchase_id: purchase.external_id }
end.to change { PurchaseIntegration.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET leave_server" do
let(:user_id) { "user-0" }
let(:integration) { create(:discord_integration) }
let(:product) { create(:product, active_integrations: [integration]) }
let(:purchase) { create(:purchase, link: product) }
it "removes member from server if integration is active" do
create(:purchase_integration, integration:, purchase:, discord_user_id: user_id)
WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 204)
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(-1)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "server_name" => "Gaming" })
end
it "marks the purchase integration as deleted if the Discord server is deleted" do
create(:purchase_integration, integration:, purchase:, discord_user_id: user_id)
WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(exception: Discordrb::Errors::UnknownServer)
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(-1)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "server_name" => "Gaming" })
end
it "fails if purchase_id is not passed" do
expect do
get :leave_server, format: :json, params: {}
end.to change { purchase.live_purchase_integrations.reload.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if purchased product does not have an integration" do
purchase = create(:purchase)
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if purchased product does not have an activated integration" do
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if call to discord api fails" do
WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(status: 500)
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if Discord raises a permissions error" do
create(:purchase_integration, integration:, purchase:, discord_user_id: user_id)
WebMock.stub_request(:delete, "#{Discordrb::API.api_base}/guilds/0/members/#{user_id}").to_return(exception: Discordrb::Errors::NoPermission)
expect do
get :leave_server, format: :json, params: { purchase_id: purchase.external_id }
end.to change { purchase.live_purchase_integrations.reload.count }.by(0)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => 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/integrations/circle_controller_spec.rb | spec/controllers/integrations/circle_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
describe Integrations::CircleController, :vcr, :without_circle_rate_limit do
it_behaves_like "inherits from Sellers::BaseController"
let(:communities_list) do [
{ "id" => 3512, "name" => "Gumroad", }
] end
let(:space_groups_list) do [
{ "id" => 8015, "name" => "Community" },
{ "id" => 8017, "name" => "14 Day Product" },
{ "id" => 13237, "name" => "Sale Every Day" },
{ "id" => 30973, "name" => "Milestones" },
{ "id" => 30981, "name" => "Discover" },
{ "id" => 31336, "name" => "5 Day Email List Course" },
{ "id" => 33545, "name" => "Grow Your Audience Challenge" },
{ "id" => 36700, "name" => "Sale Every Day Course" },
{ "id" => 43576, "name" => "Tests" },
{ "id" => 44429, "name" => "Drafts" }
] end
let(:communities_url) { CircleApi.base_uri + "/communities" }
let(:space_groups_url) { CircleApi.base_uri + "/space_groups" }
let(:community_id_param) { { community_id: 3512 } }
before do
@user = create(:user)
sign_in @user
end
describe "GET communities" do
it "returns communities for a valid api_key" do
get :communities, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "communities" => communities_list })
end
it "fails if user is not signed in" do
sign_out @user
get :communities, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(404)
expect(response.parsed_body).to eq({ "success" => false, "error" => "Not found" })
end
it "fails if request to circle API fails" do
WebMock.stub_request(:get, communities_url).to_return(status: 500)
get :communities, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if api_key is not passed" do
get :communities, format: :json
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid response is received from circle API" do
WebMock.stub_request(:get, communities_url).to_return(status: 200, body: "invalid_error_response")
get :communities, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid API key is passed" do
get :communities, format: :json, params: { api_key: "invalid_api_key" }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET space_groups" do
it "returns space_groups for a valid api_key and community_id" do
get :space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "space_groups" => space_groups_list })
end
it "fails if user is not signed in" do
sign_out @user
get :space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(404)
expect(response.parsed_body).to eq({ "success" => false, "error" => "Not found" })
end
it "fails if request to circle API fails" do
WebMock.stub_request(:get, space_groups_url).with(query: community_id_param).to_return(status: 500)
get :space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if api_key is not passed" do
get :space_groups, format: :json, params: community_id_param
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if community_id is not passed" do
get :space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid response is received from circle API" do
WebMock.stub_request(:get, space_groups_url).with(query: community_id_param).to_return(status: 200, body: "invalid_error_response")
get :space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid API key is passed" do
get :space_groups, format: :json, params: { api_key: "invalid_api_key" }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET communities_and_space_groups" do
it "returns communities_and_space_groups for a valid api_key and community_id" do
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({
"success" => true,
"communities" => communities_list,
"space_groups" => space_groups_list
})
end
it "fails if user is not signed in" do
sign_out @user
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(404)
expect(response.parsed_body).to eq({ "success" => false, "error" => "Not found" })
end
it "fails if request to circle API space_groups fails" do
WebMock.stub_request(:get, space_groups_url).with(query: community_id_param).to_return(status: 500)
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if request to circle API communities fails" do
WebMock.stub_request(:get, communities_url).to_return(status: 500)
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if api_key is not passed" do
get :communities_and_space_groups, format: :json, params: community_id_param
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if community_id is not passed" do
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid response is received from circle API communities" do
WebMock.stub_request(:get, communities_url).to_return(status: 200, body: "invalid_error_response")
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid response is received from circle API space_groups" do
WebMock.stub_request(:get, space_groups_url).with(query: community_id_param).to_return(status: 200, body: "invalid_error_response")
get :communities_and_space_groups, format: :json, params: { api_key: GlobalConfig.get("CIRCLE_API_KEY") }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if invalid API key is passed" do
get :communities_and_space_groups, format: :json, params: { api_key: "invalid_api_key" }.merge(community_id_param)
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => 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/integrations/zoom_controller_spec.rb | spec/controllers/integrations/zoom_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Integrations::ZoomController do
before do
sign_in create(:user)
end
let(:authorization_code) { "test_code" }
let(:oauth_request_body) do
{
grant_type: "authorization_code",
code: authorization_code,
redirect_uri: oauth_redirect_integrations_zoom_index_url
}
end
let(:oauth_request_header) do
client_id = GlobalConfig.get("ZOOM_CLIENT_ID")
client_secret = GlobalConfig.get("ZOOM_CLIENT_SECRET")
token = Base64.strict_encode64("#{client_id}:#{client_secret}")
{ "Authorization" => "Basic #{token}", "Content-Type" => "application/x-www-form-urlencoded" }
end
let(:zoom_id) { "0" }
let(:zoom_email) { "test@zoom.com" }
let(:access_token) { "test_access_token" }
let(:refresh_token) { "test_refresh_token" }
describe "GET account_info" do
it "returns user account information for a valid oauth code" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token:, refresh_token: }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{ZoomApi.base_uri}/users/me").
with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 200,
body: { id: zoom_id, email: zoom_email }.to_json,
headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "user_id" => zoom_id, "email" => zoom_email, "access_token" => access_token, "refresh_token" => refresh_token })
end
it "fails if oauth authorization fails" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 500)
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have access token" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { refresh_token: }.to_json,
headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have refresh token" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token: }.to_json,
headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user identification fails" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token:, refresh_token: }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{ZoomApi.base_uri}/users/me").
with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 401)
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user id is not present" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token:, refresh_token: }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{ZoomApi.base_uri}/users/me").
with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 200,
body: { email: zoom_email }.to_json,
headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user email is not present" do
WebMock.stub_request(:post, ZoomApi::ZOOM_OAUTH_URL).
with(body: oauth_request_body, headers: oauth_request_header).
to_return(status: 200,
body: { access_token:, refresh_token: }.to_json,
headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{ZoomApi.base_uri}/users/me").
with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 200,
body: { id: zoom_id }.to_json,
headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET oauth_redirect" do
it "returns successful response if code is present" do
get :oauth_redirect, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
end
it "fails if code is not present" do
get :oauth_redirect, format: :json
expect(response.status).to eq(400)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/integrations/google_calendar_controller_spec.rb | spec/controllers/integrations/google_calendar_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Integrations::GoogleCalendarController do
before do
sign_in create(:user)
end
let(:authorization_code) { "test_code" }
let(:oauth_request_body) do
{
grant_type: "authorization_code",
code: authorization_code,
redirect_uri: oauth_redirect_integrations_google_calendar_index_url,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}
end
let(:calendar_id) { "0" }
let(:calendar_summary) { "Holidays" }
let(:access_token) { "test_access_token" }
let(:refresh_token) { "test_refresh_token" }
let(:email) { "hi@gmail.com" }
describe "GET account_info" do
it "returns user account information for a valid oauth code" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 200, body: { access_token:, refresh_token: }.to_json, headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/oauth2/v2/userinfo").with(query: { access_token: }).
to_return(status: 200, body: { email: }.to_json, headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "access_token" => access_token, "refresh_token" => refresh_token, "email" => email })
end
it "fails if oauth authorization fails" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 500)
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have access token" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 200, body: { refresh_token: }.to_json, headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if oauth authorization response does not have refresh token" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 200, body: { access_token: }.to_json, headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user info request fails" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 200, body: { access_token:, refresh_token: }.to_json, headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/oauth2/v2/userinfo").with(query: { access_token: }).to_return(status: 404)
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if user info response does not have email" do
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").with(body: oauth_request_body).
to_return(status: 200, body: { access_token:, refresh_token: }.to_json, headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/oauth2/v2/userinfo").with(query: { access_token: }).
to_return(status: 200, body: {}.to_json, headers: { content_type: "application/json" })
get :account_info, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
describe "GET calendar_list" do
it "returns list of calendars from the google account associated with the access_token" do
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 200, body: {
items: [
{ id: "0", summary: "Holidays", meta: "somemeta" },
{ id: "1", summary: "Work", meta: "somemeta2" },
{ id: "2", summary: "Personal", meta: "somemeta3" }]
}.to_json, headers: { content_type: "application/json" })
get :calendar_list, format: :json, params: { access_token:, refresh_token: }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "calendar_list" => [{ "id" => "0", "summary" => "Holidays" }, { "id" => "1", "summary" => "Work" }, { "id" => "2", "summary" => "Personal" }] })
end
it "fails if the Google API for calendar list returns an error" do
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 404, headers: { content_type: "application/json" })
get :calendar_list, format: :json, params: { access_token:, refresh_token: }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
describe "uses refresh_token if access_token is expired" do
it "returns list of calendars from the google account associated with the access_token" do
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 401, headers: { content_type: "application/json" })
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").
with(
body: {
grant_type: "refresh_token",
refresh_token:,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}).
to_return(status: 200, body: {
access_token: "fresh_access_token",
expires_in: 3600
}.to_json, headers: { content_type: "application/json" })
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer fresh_access_token" }).
to_return(status: 200, body: {
items: [
{ id: "0", summary: "Holidays", meta: "somemeta" },
{ id: "1", summary: "Work", meta: "somemeta2" },
{ id: "2", summary: "Personal", meta: "somemeta3" }]
}.to_json, headers: { content_type: "application/json" })
get :calendar_list, format: :json, params: { access_token:, refresh_token: }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => true, "calendar_list" => [{ "id" => "0", "summary" => "Holidays" }, { "id" => "1", "summary" => "Work" }, { "id" => "2", "summary" => "Personal" }] })
end
it "fails if request for refresh token fails" do
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 401, headers: { content_type: "application/json" })
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").
with(
body: {
grant_type: "refresh_token",
refresh_token:,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}).
to_return(status: 400, headers: { content_type: "application/json" })
get :calendar_list, format: :json, params: { access_token:, refresh_token: }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
it "fails if refresh token response does not have access token" do
WebMock.stub_request(:get, "#{GoogleCalendarApi.base_uri}/calendar/v3/users/me/calendarList").with(headers: { "Authorization" => "Bearer #{access_token}" }).
to_return(status: 401, headers: { content_type: "application/json" })
WebMock.stub_request(:post, "#{GoogleCalendarApi::GOOGLE_CALENDAR_OAUTH_URL}/token").
with(
body: {
grant_type: "refresh_token",
refresh_token:,
client_id: GlobalConfig.get("GOOGLE_CLIENT_ID"),
client_secret: GlobalConfig.get("GOOGLE_CLIENT_SECRET"),
}).
to_return(status: 200, body: { expires_in: 3600 }.to_json, headers: { content_type: "application/json" })
get :calendar_list, format: :json, params: { access_token:, refresh_token: }
expect(response.status).to eq(200)
expect(response.parsed_body).to eq({ "success" => false })
end
end
end
describe "GET oauth_redirect" do
it "returns successful response if code is present" do
get :oauth_redirect, format: :json, params: { code: authorization_code }
expect(response.status).to eq(200)
end
it "fails if code is not present" do
get :oauth_redirect, format: :json
expect(response.status).to eq(400)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/user/omniauth_callbacks_controller_spec.rb | spec/controllers/user/omniauth_callbacks_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::OmniauthCallbacksController do
ACCOUNT_DELETION_ERROR_MSG = "You cannot log in because your account was permanently deleted. "\
"Please sign up for a new account to start selling!"
before do
request.env["devise.mapping"] = Devise.mappings[:user]
end
def fetch_json(service)
JSON.parse(File.open("#{Rails.root}/spec/support/fixtures/#{service}_omniauth.json").read)
end
def safe_redirect_path(path, allow_subdomain_host: true)
SafeRedirectPathService.new(path, request, allow_subdomain_host:).process
end
describe "#stripe_connect", :vcr do
let(:stripe_uid) { "acct_1SOb0DEwFhlcVS6d" }
let(:stripe_auth) do
OmniAuth::AuthHash.new(
uid: stripe_uid,
credentials: { token: "tok" },
info: { email: "stripe.connect@gum.co", stripe_publishable_key: "pk_key" },
extra: { extra_info: { country: "SG" }, raw_info: { country: "SG" } }
)
end
before do
request.env["omniauth.auth"] = stripe_auth
end
shared_examples "stripe connect user creation" do
it "creates user if none exists" do
expect { post :stripe_connect }.to change { User.count }.by(1)
user = User.last
expect(user.email).to eq("stripe.connect@gum.co")
expect(user.confirmed?).to be true
expect(response).to redirect_to safe_redirect_path(two_factor_authentication_path(next: oauth_completions_stripe_path))
end
it "redirects directly to completion when user has no email" do
request.env["omniauth.auth"]["info"].delete "email"
request.env["omniauth.auth"]["extra"]["raw_info"].delete "email"
expect { post :stripe_connect }.to change { User.count }.by(1)
user = User.last
expect(user.email).to be_nil
expect(controller.user_signed_in?).to be true
expect(response).to redirect_to safe_redirect_path(oauth_completions_stripe_path)
end
it "requires 2FA when user has email" do
post :stripe_connect
user = User.last
expect(user.email).to eq("stripe.connect@gum.co")
expect(controller.user_signed_in?).to be false
expect(response).to redirect_to safe_redirect_path(two_factor_authentication_path(next: oauth_completions_stripe_path))
end
it "does not create a new user if the email is already taken" do
create(:user, email: "stripe.connect@gum.co")
expect { post :stripe_connect }.not_to change { User.count }
expect(flash[:alert]).to eq "An account already exists with this email."
expect(response).to redirect_to send("#{referer}_url")
end
end
context "when referer is payments settings" do
before do
request.env["omniauth.params"] = { "referer" => settings_payments_path }
end
it "throws error if stripe account is from an unsupported country" do
request.env["omniauth.auth"]["uid"] = "acct_1SOk0BEsYunTuUHD"
user = create(:user)
allow(controller).to receive(:current_user).and_return(user)
post :stripe_connect
expect(user.reload.stripe_connect_account).to be(nil)
expect(flash[:alert]).to eq "Sorry, Stripe Connect is not supported in Malaysia yet."
expect(response).to redirect_to settings_payments_url
end
it "throws error if creator already has another stripe account connected" do
user = create(:user)
stripe_connect_account = create(:merchant_account_stripe_connect, user:, charge_processor_merchant_id: "acct_1SOb0DEwFhlcVS6d")
allow(controller).to receive(:current_user).and_return(user)
expect { post :stripe_connect }.not_to change { MerchantAccount.count }
expect(user.reload.stripe_connect_account).to eq(stripe_connect_account)
expect(flash[:alert]).to eq "You already have another Stripe account connected with your Gumroad account."
expect(response).to redirect_to settings_payments_url
end
end
context "when referer is login" do
let(:referer) { "login" }
before { request.env["omniauth.params"] = { "referer" => login_path } }
include_examples "stripe connect user creation"
it "does not log in admin user" do
create(:merchant_account_stripe_connect, user: create(:admin_user), charge_processor_merchant_id: stripe_uid)
post :stripe_connect
expect(flash[:alert]).to eq "You're an admin, you can't login with Stripe."
expect(response).to redirect_to login_url
end
it "does not allow user to login if the account is deleted" do
create(:merchant_account_stripe_connect, user: create(:user, deleted_at: Time.current), charge_processor_merchant_id: stripe_uid)
post :stripe_connect
expect(flash[:alert]).to eq ACCOUNT_DELETION_ERROR_MSG
expect(response).to redirect_to login_url
end
end
context "when referer is signup" do
let(:referer) { "signup" }
before { request.env["omniauth.params"] = { "referer" => signup_path } }
include_examples "stripe connect user creation"
it "associates past purchases with the same email to the new user" do
email = request.env["omniauth.auth"]["info"]["email"]
purchase1 = create(:purchase, email:)
purchase2 = create(:purchase, email:)
expect(purchase1.purchaser_id).to be_nil
expect(purchase2.purchaser_id).to be_nil
post :stripe_connect
user = User.last
expect(user.email).to eq("stripe.connect@gum.co")
expect(purchase1.reload.purchaser_id).to eq(user.id)
expect(purchase2.reload.purchaser_id).to eq(user.id)
expect(response).to redirect_to safe_redirect_path(two_factor_authentication_path(next: oauth_completions_stripe_path))
end
end
end
describe "#facebook" do
before do
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new fetch_json("facebook")
request.env["omniauth.params"] = { state: true }
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end
it "creates user if none exists" do
expect do
post :facebook
end.to change { User.count }.by(1)
user = User.last
expect(user.name).to eq "Sidharth Shanker"
expect(user.email).to match "sps2133@columbia.edu"
expect(user.global_affiliate).to be_present
end
it "associates past purchases with the same email to the new user" do
email = request.env["omniauth.auth"]["info"]["email"]
purchase1 = create(:purchase, email:)
purchase2 = create(:purchase, email:)
expect(purchase1.purchaser_id).to be_nil
expect(purchase2.purchaser_id).to be_nil
post :facebook
user = User.last
expect(purchase1.reload.purchaser_id).to eq(user.id)
expect(purchase2.reload.purchaser_id).to eq(user.id)
end
it "creates user even if there's no email address" do
request.env["omniauth.auth"]["info"].delete "email"
request.env["omniauth.auth"]["extra"]["raw_info"].delete "email"
post :facebook
user = User.last
expect(user.name).to eq "Sidharth Shanker"
expect(user.email).to_not be_present
end
describe "user is admin" do
it "does not log in user" do
allow(User).to receive(:new).and_return(create(:admin_user))
post :facebook
expect(flash[:alert]).to eq "You're an admin, you can't login with Facebook."
expect(response).to redirect_to login_url
end
end
context "when user is marked as deleted" do
let!(:user) { create(:user, facebook_uid: "509129169", deleted_at: Time.current) }
it "does not allow user to login" do
post :facebook
expect(flash[:alert]).to eq ACCOUNT_DELETION_ERROR_MSG
expect(response).to redirect_to login_url
end
end
context "when user has 2FA" do
let!(:user) { create(:user, facebook_uid: "509129169", email: "sps2133@example.com", two_factor_authentication_enabled: true) }
it "does not allow user to login with FB only" do
post :facebook
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: dashboard_path))
end
it "keeps referral intact" do
post :facebook, params: { referer: balance_path }
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: balance_path))
end
end
describe "no facebook account connected" do
it "links facebook account to existing account" do
@user = create(:user)
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new fetch_json("facebook")
request.env["omniauth.params"] = { "state" => "link_facebook_account" }
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
allow(controller).to receive(:current_user).and_return(@user)
post :facebook
@user.reload
expect(@user.facebook_uid).to_not be(nil)
end
describe "facebook account connected to different account" do
before do
@existing_facebook_account = create(:user, facebook_uid: fetch_json("facebook")["uid"])
@new_user = create(:user)
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new fetch_json("facebook")
request.env["omniauth.params"] = { "state" => "link_facebook_account" }
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
sign_in @new_user
end
it "does not link accounts if the facebook account is already linked to a gumroad account" do
expect do
post :facebook
end.to_not change {
@new_user.reload.facebook_uid
}
end
it "sets the correct flash message" do
post :facebook
expect(flash[:alert]).to eq "Your Facebook account has already been linked to a Gumroad account."
expect(response).to redirect_to user_url(@new_user)
end
end
end
describe "has no 2FA email" do
before do
user = create(:user)
allow(User).to receive(:new).and_return(user)
user.email = nil
user.save!(validate: false)
end
it "redirects directly to referrer", :vcr do
post :facebook, params: { referer: balance_path }
expect(response).to redirect_to balance_path
end
it "redirects directly to dashboard", :vcr do
post :facebook
expect(response).to redirect_to dashboard_path
end
end
context "when user is not created" do
before do
allow(User).to receive(:find_for_facebook_oauth).and_return(User.new)
end
it "redirects to the signup page with an error flash message" do
post :facebook
expect(flash[:alert]).to eq "Sorry, something went wrong. Please try again."
expect(response).to redirect_to signup_path
end
end
end
describe "#twitter" do
before do
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new fetch_json("twitter")
request.env["omniauth.auth"] = fetch_json("twitter")
request.env["omniauth.params"] = { "state" => true }
end
it "creates user if none exists", :vcr do
expect do
post :twitter
end.to change { User.count }.by(1)
user = User.last
expect(user.name).to match "Sidharth Shanker"
expect(user.email).to eq nil
expect(user.global_affiliate).to be_present
end
context "when user is admin" do
it "does not allow user to login" do
allow(User).to receive(:new).and_return(create(:admin_user))
post :twitter
expect(flash[:alert]).to eq "You're an admin, you can't login with Twitter."
expect(response).to redirect_to login_path
end
end
context "when user is marked as deleted" do
let!(:user) { create(:user, twitter_user_id: "279418691", deleted_at: Time.current) }
it "does not allow user to login" do
post :twitter
expect(flash[:alert]).to eq ACCOUNT_DELETION_ERROR_MSG
expect(response).to redirect_to login_path
end
end
context "when user has 2FA" do
let!(:user) { create(:user, twitter_user_id: "279418691", email: "sps2133@example.com", two_factor_authentication_enabled: true) }
it "does not allow user to login with Twitter only" do
post :twitter
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: dashboard_path))
end
it "keeps referral intact" do
post :twitter, params: { referer: balance_path }
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: balance_path))
end
end
describe "linking account" do
it "links twitter account to existing account", :vcr do
@user = create(:user, name: "Tim Lupton", bio: "A regular guy")
request.env["omniauth.params"] = { "state" => "link_twitter_account" }
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new fetch_json("twitter")
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
allow(controller).to receive(:current_user).and_return(@user)
post :twitter
@user.reload
expect(@user.name).to eq "Tim Lupton"
expect(@user.bio).to eq "A regular guy"
expect(@user.twitter_oauth_token).to_not be(nil)
expect(@user.twitter_oauth_secret).to_not be(nil)
expect(@user.twitter_handle).to_not be(nil)
end
it "updates the Twitter OAuth credentials on account creation", :vcr do
user = create(:user)
allow(User).to receive(:new).and_return(user)
OmniAuth.config.mock_auth[:twitter] = OmniAuth::AuthHash.new fetch_json("twitter")
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
post :twitter
user.reload
expect(user.twitter_oauth_token).to be_present
expect(user.twitter_oauth_secret).to be_present
end
end
describe "has no 2FA email" do
before do
user = create(:user)
allow(User).to receive(:new).and_return(user)
user.email = nil
user.save!(validate: false)
end
it "redirects to the settings page and ignores referrer", :vcr do
post :twitter, params: { referer: balance_path }
expect(flash[:warning]).to eq "Please enter an email address!"
expect(response).to redirect_to settings_main_path
end
end
context "when the user has unconfirmed email" do
before do
user = create(:user)
allow(User).to receive(:new).and_return(user)
user.email = nil
user.unconfirmed_email = "test@gumroad.com"
user.save!(validate: false)
end
it "redirects to the settings page with the correct warning flash message", :vcr do
post :twitter
expect(flash[:warning]).to eq "Please confirm your email address"
expect(response).to redirect_to settings_main_path
end
end
context "when user is not created" do
before do
allow(User).to receive(:find_or_create_for_twitter_oauth!).and_return(User.new)
end
it "redirects to the signup page with an error flash message" do
post :twitter
expect(flash[:alert]).to eq "Sorry, something went wrong. Please try again."
expect(response).to redirect_to signup_path
end
end
end
describe "#google_oauth2" do
before do
OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new fetch_json("google")
request.env["omniauth.auth"] = fetch_json("google")
request.env["omniauth.params"] = { "state" => true }
end
it "creates user if none exists", :vcr do
expect do
post :google_oauth2
end.to change { User.count }.by(1)
user = User.last
expect(user.name).to match "Paulius Dragunas"
expect(user.global_affiliate).to be_present
end
context "when user is admin" do
it "does not allow user to login" do
allow(User).to receive(:new).and_return(create(:admin_user))
post :google_oauth2
expect(flash[:alert]).to eq "You're an admin, you can't login with Google."
expect(response).to redirect_to login_path
end
end
context "when user is marked as deleted" do
let!(:user) { create(:user, google_uid: "101656774483284362141", deleted_at: Time.current) }
it "does not allow user to login" do
post :google_oauth2
expect(flash[:alert]).to eq ACCOUNT_DELETION_ERROR_MSG
expect(response).to redirect_to login_path
end
end
context "when user has 2FA" do
let!(:user) { create(:user, google_uid: "101656774483284362141", email: "pdragunas@example.com", two_factor_authentication_enabled: true) }
it "does not allow user to login with Google only" do
post :google_oauth2
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: dashboard_path))
end
it "keeps referral intact" do
post :google_oauth2, params: { referer: balance_path }
expect(response).to redirect_to CGI.unescape(two_factor_authentication_path(next: balance_path))
end
end
context "linking account" do
it "links google account to existing account", :vcr do
@user = create(:user, email: "pdragunas@example.com")
OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new fetch_json("google")
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
allow(controller).to receive(:current_user).and_return(@user)
post :google_oauth2
@user.reload
expect(@user.name).to eq "Paulius Dragunas"
expect(@user.email).to eq "pdragunas@example.com"
expect(@user.google_uid).to eq "101656774483284362141"
end
end
context "when user is not created" do
shared_examples "redirects to signup with error message" do
it "redirects to the signup page with an error flash message" do
post :google_oauth2
expect(flash[:alert]).to eq "Sorry, something went wrong. Please try again."
expect(response).to redirect_to signup_path
end
end
context "when the user is not persisted" do
before { allow(User).to receive(:find_or_create_for_google_oauth2).and_return(User.new) }
include_examples "redirects to signup with error message"
end
context "when there's an error creating the user" do
before { allow(User).to receive(:find_or_create_for_google_oauth2).and_return(nil) }
include_examples "redirects to signup with 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/user/invalidate_active_sessions_controller_spec.rb | spec/controllers/user/invalidate_active_sessions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::InvalidateActiveSessionsController do
describe "PUT update" do
let(:user) { create(:user) }
let(:oauth_application) { create(:oauth_application, uid: OauthApplication::MOBILE_API_OAUTH_APPLICATION_UID) }
let!(:active_access_token_one) { create("doorkeeper/access_token", application: oauth_application, resource_owner_id: user.id, scopes: "mobile_api") }
let!(:active_access_token_two) { create("doorkeeper/access_token", application: oauth_application, resource_owner_id: user.id, scopes: "mobile_api") }
let!(:active_access_token_of_another_user) { create("doorkeeper/access_token", application: oauth_application, scopes: "mobile_api") }
context "when user is not signed in" do
it "redirects to the login page" do
put :update
expect(response).to_not be_successful
expect(response).to redirect_to(login_path(next: user_invalidate_active_sessions_path))
end
end
context "when user is signed in" do
before(:each) do
sign_in user
end
it "updates user's 'last_active_sessions_invalidated_at' field and signs out the user" do
travel_to(DateTime.current) do
expect do
put :update
end.to change { user.reload.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current)
.and change { controller.logged_in_user }.from(user).to(nil)
.and change { active_access_token_one.reload.revoked_at }.from(nil).to(DateTime.current)
.and change { active_access_token_two.reload.revoked_at }.from(nil).to(DateTime.current)
expect(active_access_token_of_another_user.reload.revoked_at).to be_nil
end
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(flash[:notice]).to eq("You have been signed out from all your active sessions. Please login again.")
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/user/passwords_controller_spec.rb | spec/controllers/user/passwords_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe User::PasswordsController do
before do
request.env["devise.mapping"] = Devise.mappings[:user]
@user = create(:user)
end
describe "#new" do
it "404s" do
expect { get :new }.to raise_error(ActionController::RoutingError)
end
end
describe "#create" do
it "sends an email to the user" do
post(:create, params: { user: { email: @user.email } })
expect(response).to be_successful
end
it "returns a json error if email is blank even if matching user exists" do
create(:user, email: "", provider: :twitter)
post(:create, params: { user: { email: "" } })
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["error_message"]).to eq "An account does not exist with that email."
end
it "returns a json error if email is not valid" do
post(:create, params: { user: { email: "this is no sort of valid email address" } })
expect(response).to have_http_status(:unprocessable_content)
expect(response.parsed_body["error_message"]).to eq "An account does not exist with that email."
end
end
describe "#edit" do
it "shows a form for a valid token" do
get(:edit, params: { reset_password_token: @user.send_reset_password_instructions })
expect(response).to be_successful
end
describe "should fail when errors" do
it "shows an error for an invalid token" do
get :edit, params: { reset_password_token: "invalid" }
expect(flash[:alert]).to eq "That reset password token doesn't look valid (or may have expired)."
expect(response).to redirect_to root_url
end
end
end
describe "#update" do
it "logs in after successful pw reset" do
post :update, params: { user: { password: "password_new", password_confirmation: "password_new", reset_password_token: @user.send_reset_password_instructions } }
expect(@user.reload.valid_password?("password_new")).to be(true)
expect(flash[:notice]).to eq "Your password has been reset, and you're now logged in."
expect(response).to be_successful
end
it "invalidates all active sessions after successful password reset" do
expect_any_instance_of(User).to receive(:invalidate_active_sessions!).and_call_original
post :update, params: { user: { password: "password_new", password_confirmation: "password_new", reset_password_token: @user.send_reset_password_instructions } }
end
describe "should fail when there are errors" do
let(:old_password) { @user.password }
it "shows error after unsuccessful pw reset" do
@user.send_reset_password_instructions
post :update, params: { user: { password: "password_new", password_confirmation: "password_no", reset_password_token: @user.send_reset_password_instructions } }
expect(@user.password).to eq old_password
expect(response.parsed_body).to eq({ error_message: "Those two passwords didn't match." }.as_json)
end
context "when specifying a compromised password", :vcr do
it "fails with an error" do
with_real_pwned_password_check do
post :update, params: { user: { password: "password", password_confirmation: "password", reset_password_token: @user.send_reset_password_instructions } }
end
expect(response.parsed_body).to eq({ error_message: "Password has previously appeared in a data breach as per haveibeenpwned.com and should never be used. Please choose something harder to guess." }.as_json)
end
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/custom_domain/verifications_controller_spec.rb | spec/controllers/custom_domain/verifications_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe CustomDomain::VerificationsController do
it_behaves_like "inherits from Sellers::BaseController"
describe "POST create" do
let(:seller) { create(:named_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) { :show? }
end
context "when a blank domain is specified" do
it "returns error response" do
post :create, format: :json, params: { domain: "" }
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(false)
end
end
context "when the specified domain is correctly configured" do
let(:domain) { "product.example.com" }
before do
allow_any_instance_of(Resolv::DNS)
.to receive(:getresources)
.with(domain, Resolv::DNS::Resource::IN::CNAME)
.and_return([double(name: CUSTOM_DOMAIN_CNAME)])
end
it "returns success response" do
post :create, params: { domain: }, as: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["message"]).to eq("product.example.com domain is correctly configured!")
end
context "when the specified domain is for a product" do
let(:product) { create(:product) }
it "returns a success response" do
post :create, params: { domain:, product_id: product.external_id }, as: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["message"]).to eq("product.example.com domain is correctly configured!")
end
context "when the product already has a custom domain" do
let!(:custom_domain) { create(:custom_domain, domain: "domain.example.com", user: nil, product:) }
it "verifies the new domain and returns a success response" do
post :create, params: { domain:, product_id: product.external_id }, as: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["message"]).to eq("product.example.com domain is correctly configured!")
end
end
context "when the specified domain matches another product's custom domain" do
let(:another_product) { create(:product) }
let!(:custom_domain) { create(:custom_domain, domain: "product.example.com", user: nil, product: another_product) }
it "returns error response with message" do
post :create, params: { domain:, product_id: product.external_id }, as: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("The custom domain is already in use.")
end
end
end
end
context "when the specified domain is not configured" do
let(:domain) { "store.example.com" }
before do
allow_any_instance_of(Resolv::DNS)
.to receive(:getresources)
.with(domain, anything)
.and_return([])
allow_any_instance_of(Resolv::DNS)
.to receive(:getresources)
.with(CUSTOM_DOMAIN_CNAME, anything)
.and_return([double(address: "100.0.0.1")])
allow_any_instance_of(Resolv::DNS)
.to receive(:getresources)
.with(CUSTOM_DOMAIN_STATIC_IP_HOST, Resolv::DNS::Resource::IN::A)
.and_return([double(address: "100.0.0.2")])
end
it "returns success response" do
post :create, format: :json, params: { domain: }
expect(response).to have_http_status(:ok)
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["message"]).to eq("Domain verification failed. Please make sure you have correctly configured the DNS record for store.example.com.")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/third_party_analytics_controller_spec.rb | spec/controllers/settings/third_party_analytics_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 Settings::ThirdPartyAnalyticsController, type: :controller, inertia: true do
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Settings::ThirdPartyAnalytics::UserPolicy do
let(:record) { seller }
end
describe "GET show" do
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/ThirdPartyAnalytics/Show")
settings_presenter = SettingsPresenter.new(pundit_user: controller.pundit_user)
expected_props = {
third_party_analytics: settings_presenter.third_party_analytics_props,
products: seller.links.alive.map { |product| { permalink: product.unique_permalink, name: product.name } },
}
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
google_analytics_id = "G-1234567"
facebook_pixel_id = "123456789"
facebook_meta_tag = '<meta name="facebook-domain-verification" content="dkd8382hfdjs" />'
context "when all of the fields are valid" do
it "returns a successful response" do
put :update, params: {
user: {
disable_third_party_analytics: false,
google_analytics_id:,
facebook_pixel_id:,
skip_free_sale_analytics: true,
enable_verify_domain_third_party_services: true,
facebook_meta_tag:,
}
}
expect(response).to redirect_to(settings_third_party_analytics_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Changes saved!")
seller.reload
expect(seller.disable_third_party_analytics).to eq(false)
expect(seller.google_analytics_id).to eq(google_analytics_id)
expect(seller.facebook_pixel_id).to eq(facebook_pixel_id)
expect(seller.skip_free_sale_analytics).to eq(true)
expect(seller.enable_verify_domain_third_party_services).to eq(true)
expect(seller.facebook_meta_tag).to eq(facebook_meta_tag)
end
end
context "when a field is invalid" do
it "returns an error response and doesn't persist changes" do
put :update, params: {
user: {
disable_third_party_analytics: false,
google_analytics_id: "bad",
facebook_pixel_id:,
skip_free_sale_analytics: true,
enable_verify_domain_third_party_services: true,
facebook_meta_tag:,
}
}
expect(response).to redirect_to(settings_third_party_analytics_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Please enter a valid Google Analytics ID")
seller.reload
expect(seller.disable_third_party_analytics).to eq(false)
expect(seller.google_analytics_id).to be_nil
expect(seller.facebook_pixel_id).to be_nil
expect(seller.skip_free_sale_analytics).to eq(false)
expect(seller.enable_verify_domain_third_party_services).to eq(false)
expect(seller.facebook_meta_tag).to be_nil
end
end
context "when updating throws an error" do
it "returns an error response" do
allow_any_instance_of(User).to receive(:update).and_raise(StandardError)
put :update, params: {}
expect(response).to redirect_to(settings_third_party_analytics_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Something broke. We're looking into what happened. Sorry about this!")
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/settings/stripe_controller_spec.rb | spec/controllers/settings/stripe_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Settings::StripeController, :vcr do
describe "POST disconnect" do
before do
@creator = create(:user)
create(:user_compliance_info, user: @creator)
Feature.activate_user(:merchant_migration, @creator)
create(:merchant_account_stripe_connect, user: @creator)
expect(@creator.stripe_connect_account).to be_present
expect(@creator.has_stripe_account_connected?).to be true
sign_in @creator
end
context "when stripe disconnect is allowed" do
it "marks the connected Stripe merchant account as deleted" do
expect_any_instance_of(User).to receive(:stripe_disconnect_allowed?).once.and_return true
post :disconnect
expect(response.parsed_body["success"]).to eq(true)
expect(@creator.stripe_connect_account).to be nil
expect(@creator.has_stripe_account_connected?).to be false
end
it "reactivates creator's old gumroad-controlled Stripe account associated with their unpaid balance" do
stripe_account = create(:merchant_account_stripe_canada, user: @creator)
stripe_account.delete_charge_processor_account!
create(:balance, user: @creator, merchant_account: stripe_account)
expect(@creator.stripe_account).to be nil
expect_any_instance_of(User).to receive(:stripe_disconnect_allowed?).once.and_return true
post :disconnect
expect(response.parsed_body["success"]).to eq(true)
expect(@creator.has_stripe_account_connected?).to be false
expect(@creator.stripe_connect_account).to be nil
expect(@creator.stripe_account).to eq stripe_account
end
it "reactivates creator's old gumroad-controlled Stripe account that's associated with the active bank account" do
stripe_account = create(:merchant_account_stripe_canada, user: @creator)
stripe_account.delete_charge_processor_account!
create(:ach_account, user: @creator, stripe_connect_account_id: stripe_account.charge_processor_merchant_id)
expect(@creator.stripe_account).to be nil
expect_any_instance_of(User).to receive(:stripe_disconnect_allowed?).once.and_return true
post :disconnect
expect(response.parsed_body["success"]).to eq(true)
expect(@creator.has_stripe_account_connected?).to be false
expect(@creator.stripe_connect_account).to be nil
expect(@creator.stripe_account).to eq 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/settings/team_controller_spec.rb | spec/controllers/settings/team_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 Settings::TeamController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Settings::Team::UserPolicy do
let(:record) { seller }
end
describe "GET show" do
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Team/Show")
SettingsPresenter.new(pundit_user: controller.pundit_user)
team_presenter = Settings::TeamPresenter.new(pundit_user: controller.pundit_user)
expected_props = {
member_infos: team_presenter.member_infos.map(&:to_hash),
can_invite_member: Pundit.policy!(controller.pundit_user, [:settings, :team, TeamInvitation]).create?,
}
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
# Convert member_infos objects to hashes for comparison
actual_props[:member_infos] = actual_props[:member_infos].map(&:to_hash) if actual_props[:member_infos]
expect(actual_props).to eq(expected_props)
end
context "when user does not have an email" do
before do
seller.update!(
provider: :twitter,
twitter_user_id: "123",
email: nil
)
end
it "redirects" do
get :show
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Your Gumroad account doesn't have an email associated. Please assign and verify your email, and try again.")
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/settings/main_controller_spec.rb | spec/controllers/settings/main_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 Settings::MainController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
before do
sign_in seller
end
it_behaves_like "authorize called for controller", Settings::Main::UserPolicy do
let(:record) { seller }
end
describe "GET show" do
include_context "with user signed in as admin for seller"
let(:pundit_user) { SellerContext.new(user: user_with_role_for_seller, seller:) }
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Main/Show")
settings_presenter = SettingsPresenter.new(pundit_user:)
expected_props = settings_presenter.main_props
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
let (:user_params) do
{ seller_refund_policy: { max_refund_period_in_days: "30", fine_print: nil } }
end
it "submits the form successfully" do
put :update, params: { user: user_params.merge(email: "hello@example.com") }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(seller.reload.unconfirmed_email).to eq("hello@example.com")
end
it "returns error message when StandardError is raised" do
allow_any_instance_of(User).to receive(:save!).and_raise(StandardError)
put :update, params: { user: user_params.merge(email: "hello@example.com") }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Something broke. We're looking into what happened. Sorry about this!")
end
describe "expires products" do
let(:product) { create(:product, user: seller) }
before do
product.user.update!(enable_recurring_subscription_charge_email: true)
Rails.cache.write(product.scoped_cache_key("en"), "<html>Hello</html>")
product.product_cached_values.create!
end
it "expires the user's products", :sidekiq_inline do
put :update, params: { user: user_params.merge(enable_recurring_subscription_charge_email: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(Rails.cache.read(product.scoped_cache_key("en"))).to be(nil)
expect(product.reload.product_cached_values.fresh).to eq([])
end
end
it "sets error message and render show on invalid record" do
put :update, params: { user: user_params.merge(email: "BAD EMAIL") }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Email is invalid")
end
describe "email changing" do
describe "email is changed to something new" do
before do
seller.update_columns(email: "test@gumroad.com", unconfirmed_email: "test@gumroad.com")
end
it "sets unconfirmed_email column" do
expect { put :update, params: { user: user_params.merge(email: "new@gumroad.com") } }.to change {
seller.reload.unconfirmed_email
}.from("test@gumroad.com").to("new@gumroad.com")
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "does not change email column" do
expect do
put :update, params: { user: user_params.merge(email: "new@gumroad.com") }
end.to_not change { seller.reload.email }.from("test@gumroad.com")
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "sends email_changed notification" do
expect do
put :update, params: { user: user_params.merge(email: "another+email@example.com") }
end.to have_enqueued_mail(UserSignupMailer, :email_changed)
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
describe "email is changed back to a confirmed email" do
before(:each) do
seller.update_columns(email: "test@gumroad.com", unconfirmed_email: "new@gumroad.com")
end
it "changes the unconfirmed_email to nil" do
expect do
put :update, params: { user: user_params.merge(email: "test@gumroad.com") }
end.to change {
seller.reload.unconfirmed_email
}.from("new@gumroad.com").to(nil)
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "doesn't send email_changed notification" do
expect do
put :update, params: { user: user_params.merge(email: seller.email) }
end.not_to have_enqueued_mail(UserSignupMailer, :email_changed)
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
end
it "updates the enable_free_downloads_email flag correctly" do
seller.update!(enable_free_downloads_email: true)
expect do
put :update, params: { user: user_params.merge(enable_free_downloads_email: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_free_downloads_email
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(enable_free_downloads_email: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_free_downloads_email
}.from(false).to(true)
end
it "updates the enable_free_downloads_push_notification flag correctly" do
seller.update!(enable_free_downloads_push_notification: true)
expect do
put :update, params: { user: user_params.merge(enable_free_downloads_push_notification: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_free_downloads_push_notification
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(enable_free_downloads_push_notification: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_free_downloads_push_notification
}.from(false).to(true)
end
it "updates the enable_recurring_subscription_charge_email flag correctly" do
seller.update!(enable_recurring_subscription_charge_email: true)
expect do
put :update, params: { user: user_params.merge(enable_recurring_subscription_charge_email: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_recurring_subscription_charge_email
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(enable_recurring_subscription_charge_email: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_recurring_subscription_charge_email
}.from(false).to(true)
end
it "updates the enable_recurring_subscription_charge_push_notification flag correctly" do
seller.update!(enable_recurring_subscription_charge_push_notification: true)
expect do
put :update, params: { user: user_params.merge(enable_recurring_subscription_charge_push_notification: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_recurring_subscription_charge_push_notification
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(enable_recurring_subscription_charge_push_notification: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_recurring_subscription_charge_push_notification
}.from(false).to(true)
end
it "updates the enable_payment_push_notification flag correctly" do
seller.update!(enable_payment_push_notification: true)
expect do
put :update, params: { user: user_params.merge(enable_payment_push_notification: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_payment_push_notification
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(enable_payment_push_notification: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.enable_payment_push_notification
}.from(false).to(true)
end
it "updates the disable_comments_email flag correctly" do
seller.update!(disable_comments_email: true)
expect do
put :update, params: { user: user_params.merge(disable_comments_email: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.disable_comments_email
}.from(true).to(false)
expect do
put :update, params: { user: user_params.merge(disable_comments_email: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.disable_comments_email
}.from(false).to(true)
end
it "updates the disable_reviews_email flag correctly" do
expect do
put :update, params: { user: user_params.merge(disable_reviews_email: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.disable_reviews_email
}.from(false).to(true)
expect do
put :update, params: { user: user_params.merge(disable_reviews_email: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.disable_reviews_email
}.from(true).to(false)
end
it "updates the show_nsfw_products flag correctly" do
expect do
put :update, params: { user: user_params.merge(show_nsfw_products: true) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.show_nsfw_products
}.from(false).to(true)
expect do
put :update, params: { user: user_params.merge(show_nsfw_products: false) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end.to change {
seller.reload.show_nsfw_products
}.from(true).to(false)
end
describe "seller refund policy" do
context "when enabled" do
before do
seller.refund_policy.update!(max_refund_period_in_days: 0)
end
it "updates the seller refund policy fine print" do
put :update, params: { user: { seller_refund_policy: { max_refund_period_in_days: "30", fine_print: "This is a fine print" } } }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(seller.refund_policy.reload.max_refund_period_in_days).to eq(30)
expect(seller.refund_policy.fine_print).to eq("This is a fine print")
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 "does not update the seller refund policy" do
put :update, params: { user: { seller_refund_policy: { max_refund_period_in_days: "30", fine_print: "This is a fine print" } } }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(seller.refund_policy.reload.max_refund_period_in_days).to eq(0)
end
end
end
context "when not enabled" do
before do
seller.update!(refund_policy_enabled: false)
seller.refund_policy.update!(max_refund_period_in_days: 0)
end
it "does not update the seller refund policy" do
put :update, params: { user: { seller_refund_policy: { max_refund_period_in_days: "30", fine_print: "This is a fine print" } } }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(seller.refund_policy.reload.max_refund_period_in_days).to eq(0)
expect(seller.refund_policy.fine_print).to be_nil
end
end
context "product level support emails" do
let(:product1) { create(:product, user: seller) }
let(:product2) { create(:product, user: seller) }
let(:other_seller) { create(:user) }
let(:other_product) { create(:product, user: other_seller) }
before do
Feature.activate(:product_level_support_emails)
end
it "creates new support emails with associated products" do
product_level_support_emails = [
{
email: "contact@example.com",
product_ids: [product1.external_id, product2.external_id]
},
{
email: "support@example.com",
product_ids: []
}
]
put :update, params: { user: user_params.merge(product_level_support_emails:) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(product1.reload.support_email).to eq("contact@example.com")
expect(product2.reload.support_email).to eq("contact@example.com")
end
it "fails when email isn't valid" do
product_level_support_emails = [
{ email: "invalid-email", product_ids: [product1.external_id] }
]
put :update, params: { user: user_params.merge(product_level_support_emails:) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Something broke. We're looking into what happened. Sorry about this!")
end
it "only associates products belonging to current seller" do
product_level_support_emails = [
{
email: "contact@example.com",
product_ids: [product1.external_id, other_product.external_id]
}
]
put :update, params: { user: user_params.merge(product_level_support_emails:) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(product1.reload.support_email).to eq("contact@example.com")
expect(other_product.reload.support_email).to be_nil
end
it "clears all existing support emails if param is empty" do
product1.update!(support_email: "support@example.com")
product2.update!(support_email: "support@example.com")
put :update, params: { user: user_params.merge(product_level_support_emails: []) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(product1.reload.support_email).to be_nil
expect(product2.reload.support_email).to be_nil
end
context "when product_level_support_emails feature is disabled" do
before do
Feature.deactivate(:product_level_support_emails)
end
it "does not update product support emails" do
product_level_support_emails = [
{ email: "contact@example.com", product_ids: [product1.external_id] }
]
put :update, params: { user: user_params.merge(product_level_support_emails:) }
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(product1.reload.support_email).to be_nil
end
end
end
end
end
describe "POST resend_confirmation_email" do
shared_examples_for "resends email confirmation" do
it "resends email confirmation" do
expect { post :resend_confirmation_email }
.to have_enqueued_mail(UserSignupMailer, :confirmation_instructions)
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Confirmation email resent!")
end
end
shared_examples_for "doesn't resend email confirmation" do
it "doesn't resend email confirmation" do
expect { post :resend_confirmation_email }
.not_to have_enqueued_mail(UserSignupMailer)
expect(response).to redirect_to(settings_main_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Sorry, something went wrong. Please try again.")
end
end
context "when user has email and not confirmed" do
before do
seller.update_columns(confirmed_at: nil)
end
it_behaves_like "resends email confirmation"
end
context "when user has changed email after confirmation" do
before do
seller.confirm
seller.update_attribute(:email, "some@gumroad.com")
end
it_behaves_like "resends email confirmation"
end
context "when user is confirmed" do
before do
seller.confirm
end
it_behaves_like "doesn't resend email confirmation"
end
context "when user doesn't have email" do
before do
seller.update_columns(email: nil)
end
it_behaves_like "doesn't resend email confirmation"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/password_controller_spec.rb | spec/controllers/settings/password_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 Settings::PasswordController, :vcr, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let (:user) { create(:user) }
before do
sign_in user
end
it_behaves_like "authorize called for controller", Settings::Password::UserPolicy do
let(:record) { user }
end
describe "GET show" do
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Password/Show")
expected_props = {
require_old_password: user.provider.blank?,
}
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
context "when request payload is missing" do
it "returns failure response" do
with_real_pwned_password_check do
put :update
end
expect(response).to redirect_to(settings_password_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Incorrect password.")
end
end
context "when the specified new password is not compromised" do
it "returns success response" do
with_real_pwned_password_check do
put :update, params: { user: { password: user.password, new_password: "#{user.password}-new" } }
end
expect(response).to redirect_to(settings_password_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("You have successfully changed your password.")
end
end
context "when the specified new password is compromised" do
it "returns failure response" do
with_real_pwned_password_check do
put :update, params: { user: { password: user.password, new_password: "password" } }
end
expect(response).to redirect_to(settings_password_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to be_present
end
end
it "invalidates the user's active sessions and keeps the current session active" do
travel_to(DateTime.current) do
expect do
put :update, params: { user: { password: user.password, new_password: "#{user.password}-new" } }
end.to change { user.reload.last_active_sessions_invalidated_at }.from(nil).to(DateTime.current)
expect(response).to redirect_to(settings_password_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("You have successfully changed your password.")
expect(request.env["warden"].session["last_sign_in_at"]).to eq(DateTime.current.to_i)
end
end
end
describe "PUT update with social-provided account" do
let (:user) { create(:user, provider: :facebook) }
before do
sign_in user
end
it "returns http success without checking for old password" do
with_real_pwned_password_check do
put :update, params: { user: { password: "", new_password: "#{user}-new" } }
end
expect(response).to redirect_to(settings_password_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("You have successfully changed your password.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/dismiss_ai_product_generation_promos_controller_spec.rb | spec/controllers/settings/dismiss_ai_product_generation_promos_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe Settings::DismissAiProductGenerationPromosController 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(:record) { seller }
let(:policy_method) { :generate_product_details_with_ai? }
end
context "when user is authenticated and authorized" do
before do
Feature.activate(:ai_product_generation)
seller.confirm
allow_any_instance_of(User).to receive(:sales_cents_total).and_return(15_000)
create(:payment_completed, user: seller)
end
it "dismisses the AI product generation promo alert" do
expect(seller.dismissed_create_products_with_ai_promo_alert).to be(false)
post :create
expect(response).to have_http_status(:ok)
expect(seller.reload.dismissed_create_products_with_ai_promo_alert).to be(true)
end
it "works when promo alert is already dismissed" do
seller.update!(dismissed_create_products_with_ai_promo_alert: true)
post :create
expect(response).to have_http_status(:ok)
expect(seller.reload.dismissed_create_products_with_ai_promo_alert).to be(true)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/authorized_applications_controller_spec.rb | spec/controllers/settings/authorized_applications_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 Settings::AuthorizedApplicationsController, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
let(:pundit_user) { SellerContext.new(user: user_with_role_for_seller, seller:) }
describe "GET index" do
it_behaves_like "authorize called for action", :get, :index do
let(:record) { OauthApplication }
let(:policy_klass) { Settings::AuthorizedApplications::OauthApplicationPolicy }
end
it "returns http success and renders Inertia component" do
create("doorkeeper/access_token", resource_owner_id: seller.id, scopes: "creator_api")
get :index
expect(response).to be_successful
expect(inertia.component).to eq("Settings/AuthorizedApplications/Index")
pundit_user = SellerContext.new(user: user_with_role_for_seller, seller:)
expected_props = SettingsPresenter.new(pundit_user:).authorized_applications_props
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_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/settings/advanced_controller_spec.rb | spec/controllers/settings/advanced_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 Settings::AdvancedController, :vcr, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Settings::Advanced::UserPolicy do
let(:record) { seller }
end
describe "GET show" do
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Advanced/Show")
settings_presenter = SettingsPresenter.new(pundit_user: controller.pundit_user)
expected_props = settings_presenter.advanced_props
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
it "submits the form successfully" do
put :update, params: { user: { notification_endpoint: "https://example.com" } }
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
expect(seller.reload.notification_endpoint).to eq("https://example.com")
end
it "returns error message when StandardError is raised" do
allow_any_instance_of(User).to receive(:update).and_raise(StandardError)
put :update, params: { user: { notification_endpoint: "https://example.com" } }
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Something broke. We're looking into what happened. Sorry about this!")
end
context "when params contains a domain" do
context "when logged_in_user has an existing custom_domain" do
before do
create(:custom_domain, user: seller, domain: "example-domain.com")
end
it "updates the custom_domain" do
expect do
put :update, params: { user: { enable_verify_domain_third_party_services: "0" }, domain: "test-custom-domain.gumroad.com" }
end.to change {
seller.reload.custom_domain.domain
}.from("example-domain.com").to("test-custom-domain.gumroad.com")
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
context "when domain verification fails" do
before do
seller.custom_domain.update!(failed_verification_attempts_count: 2)
allow_any_instance_of(CustomDomainVerificationService)
.to receive(:process)
.and_return(false)
end
it "does not increment the failed verification attempts count" do
expect do
put :update, params: { user: { enable_verify_domain_third_party_services: "0" }, domain: "invalid.example.com" }
end.to_not change {
seller.reload.custom_domain.failed_verification_attempts_count
}
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to be_present
end
end
end
context "when logged_in_user doesn't have an existing custom_domain" do
it "creates a new custom_domain" do
expect do
put :update, params: { user: { enable_verify_domain_third_party_services: "0" }, domain: "test-custom-domain.gumroad.com" }
end.to change { CustomDomain.alive.count }.by(1)
expect(seller.custom_domain.domain).to eq "test-custom-domain.gumroad.com"
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
end
context "when params doesn't contain a domain" do
context "when user has an existing custom_domain" do
let(:custom_domain) { create(:custom_domain, user: seller, domain: "example.com") }
it "doesn't delete the custom_domain" do
expect do
put :update, params: { user: { enable_verify_domain_third_party_services: "0" } }
end.to change {
CustomDomain.alive.count
}.by(0)
expect(custom_domain.reload.deleted_at).to be_nil
expect(seller.reload.custom_domain).to eq custom_domain
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
end
context "when domain is set to empty string in params" do
context "when user has an existing custom_domain" do
let(:custom_domain) { create(:custom_domain, user: seller, domain: "example.com") }
it "deletes the custom_domain" do
expect do
put :update, params: { user: { enable_verify_domain_third_party_services: "0" }, domain: "" }
end.to change {
custom_domain.reload.deleted?
}.from(false).to(true)
expect(seller.reload.custom_domain).to be_nil
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
context "when user doesn't have an existing custom_domain" do
it "renders success response" do
expect { put :update, params: { user: { enable_verify_domain_third_party_services: "0" }, domain: "" } }.to change { CustomDomain.alive.count }.by(0)
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
end
end
describe "mass-block customer emails" do
it "blocks the specified emails" do
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "customer1@example.com\ncustomer2@example.com" }
end.to change { seller.blocked_customer_objects.active.email.count }.by(2)
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer1@example.com", "customer2@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "does not block the specified emails if they are already blocked" do
["customer1@example.com", "customer3@example.com"].each do |email|
BlockedCustomerObject.block_email!(email:, seller_id: seller.id)
end
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "customer3@example.com\ncustomer2@example.com\ncustomer1@example.com" }
end.to change { seller.blocked_customer_objects.active.email.count }.by(1)
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer3@example.com", "customer2@example.com", "customer1@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "unblocks the emails that were previously blocked but are not specified in the 'blocked_customer_emails' param" do
BlockedCustomerObject.block_email!(email: "customer1@example.com", seller_id: seller.id)
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "customer2@example.com\njohn@example.com" }
end.to change { seller.blocked_customer_objects.active.email.count }.from(1).to(2)
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer2@example.com", "john@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "blocks an email again if it was previously blocked and then unblocked" do
BlockedCustomerObject.block_email!(email: "john@example.com", seller_id: seller.id)
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["john@example.com"])
seller.blocked_customer_objects.active.email.first.unblock!
expect(seller.blocked_customer_objects.active.email.count).to eq(0)
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "john@example.com\nsmith@example.com" }
end.to change { seller.blocked_customer_objects.active.email.count }.from(0).to(2)
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["john@example.com", "smith@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "unblocks an email for a seller even if it is blocked by another seller" do
BlockedCustomerObject.block_email!(email: "john@example.com", seller_id: seller.id)
another_seller = create(:user)
BlockedCustomerObject.block_email!(email: "john@example.com", seller_id: another_seller.id)
expect do
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "customer@example.com" }
end.to change { seller.blocked_customer_objects.active.email.pluck(:object_value) }.from(["john@example.com"]).to(["customer@example.com"])
end.to_not change { another_seller.blocked_customer_objects.active.email.pluck(:object_value) }
expect(another_seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["john@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "does not block or unblock any emails if one of the specified emails is invalid" do
BlockedCustomerObject.block_email!(email: "customer1@example.com", seller_id: seller.id)
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "john@example.com\nrob@@example.com\n\njane @example.com" }
end.to_not change { seller.blocked_customer_objects.active.email.count }
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["customer1@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("The email rob@@example.com cannot be blocked as it is invalid.")
end
it "unblocks all emails if the 'blocked_customer_emails' param is empty" do
["john@example.com", "smith@example.com"].each do |email|
BlockedCustomerObject.block_email!(email:, seller_id: seller.id)
end
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "" }
end.to change { seller.blocked_customer_objects.active.email.count }.from(2).to(0)
expect(seller.blocked_customer_objects.active.email.count).to eq(0)
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Your account has been updated!")
end
it "responds with a generic error if an unexpected error occurs" do
expect(BlockedCustomerObject).to receive(:block_email!).and_raise(ActiveRecord::RecordInvalid)
expect do
put :update, params: { user: { notification_endpoint: "" }, blocked_customer_emails: "john@example.com" }
end.to_not change { seller.blocked_customer_objects.active.email.count }
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Sorry, something went wrong. Please try again.")
end
it "blocks the specified emails even if other form fields fail validations" do
expect do
put :update, params: { user: { notification_endpoint: "https://example.com" }, blocked_customer_emails: "john@example.com\n\nrob@example.com", domain: "invalid-domain" }
end.to change { seller.blocked_customer_objects.active.email.count }.from(0).to(2)
.and change { seller.reload.notification_endpoint }.from(nil).to("https://example.com")
expect(seller.blocked_customer_objects.active.email.pluck(:object_value)).to match_array(["john@example.com", "rob@example.com"])
expect(response).to redirect_to(settings_advanced_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("invalid-domain is not a valid domain name.")
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/settings/profile_controller_spec.rb | spec/controllers/settings/profile_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 Settings::ProfileController, :vcr, type: :controller, inertia: true do
let(:seller) { create(:named_seller) }
let(:pundit_user) { SellerContext.new(user: user_with_role_for_seller, seller:) }
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Settings::ProfilePolicy do
let(:record) { :profile }
end
describe "GET show" do
it "returns successful response with Inertia page data" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Profile/Show")
settings_presenter = SettingsPresenter.new(pundit_user: controller.pundit_user)
profile_presenter = ProfilePresenter.new(pundit_user: controller.pundit_user, seller:)
expected_props = settings_presenter.profile_props.merge(
profile_presenter.profile_settings_props(request:)
)
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
before do
sign_in seller
request.headers["X-Inertia"] = "true"
end
it "submits the form successfully" do
put :update, params: { user: { name: "New name", username: "gum" } }
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Changes saved!")
expect(seller.reload.name).to eq("New name")
expect(seller.username).to eq("gum")
end
it "converts a blank username to nil" do
seller.username = "oldusername"
seller.save
expect { put :update, params: { user: { username: "" } } }.to change {
seller.reload.read_attribute(:username)
}.from("oldusername").to(nil)
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Changes saved!")
end
it "performs model validations" do
put :update, params: { user: { username: "ab" } }
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("Username is too short (minimum is 3 characters)")
end
describe "when the user has not confirmed their email address" do
before do
seller.update!(confirmed_at: nil)
end
it "returns an error" do
put :update, params: { user: { name: "New name" } }
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("You have to confirm your email address before you can do that.")
end
end
it "saves tabs and cleans up orphan sections" do
section1 = create(:seller_profile_products_section, seller:)
section2 = create(:seller_profile_posts_section, seller:)
create(:seller_profile_posts_section, seller:)
create(:seller_profile_posts_section, seller:, product: create(:product))
seller.avatar.attach(file_fixture("test.png"))
put :update, params: { tabs: [{ name: "Tab 1", sections: [section1.external_id] }, { name: "Tab 2", sections: [section2.external_id] }, { name: "Tab 3", sections: [] }] }
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Changes saved!")
expect(seller.seller_profile_sections.count).to eq 3
expect(seller.seller_profile_sections.on_profile.count).to eq 2
expect(seller.reload.seller_profile.json_data["tabs"]).to eq [{ name: "Tab 1", sections: [section1.id] }, { name: "Tab 2", sections: [section2.id] }, { name: "Tab 3", sections: [] }].as_json
expect(seller.avatar.attached?).to be(true) # Ensure the avatar remains attached
end
it "returns an error if the corresponding blob for the provided 'profile_picture_blob_id' is already removed" do
seller.avatar.attach(file_fixture("test.png"))
signed_id = seller.avatar.signed_id
# Purging an ActiveStorage::Blob in test environment returns Aws::S3::Errors::AccessDenied
allow_any_instance_of(ActiveStorage::Blob).to receive(:purge).and_return(nil)
allow(ActiveStorage::Blob).to receive(:find_signed).with(signed_id).and_return(nil)
seller.avatar.purge
put :update, params: { user: { name: "New name" }, profile_picture_blob_id: signed_id }
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :found
expect(flash[:alert]).to eq("The logo is already removed. Please refresh the page and try again.")
end
it "regenerates the subscribe preview when the avatar changes" do
allow_any_instance_of(User).to receive(:generate_subscribe_preview).and_call_original
blob = ActiveStorage::Blob.create_and_upload!(
io: fixture_file_upload("smilie.png"),
filename: "smilie.png",
)
expect do
put :update, params: {
profile_picture_blob_id: blob.signed_id
}
end.to change { GenerateSubscribePreviewJob.jobs.size }.by(1)
expect(response).to redirect_to(settings_profile_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Changes saved!")
expect(GenerateSubscribePreviewJob).to have_enqueued_sidekiq_job(seller.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/settings/payments_controller_spec.rb | spec/controllers/settings/payments_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 Settings::PaymentsController, :vcr, type: :controller, inertia: true do
it_behaves_like "inherits from Sellers::BaseController"
let(:seller) { create(:named_seller) }
before :each do
create(:user_compliance_info, country: "United States", user: seller)
allow_any_instance_of(User).to receive(:external_id).and_return("6")
end
before do
sign_in seller
end
context "when logged in user is admin of seller account" do
include_context "with user signed in as admin for seller"
it_behaves_like "authorize called for controller", Settings::Payments::UserPolicy do
let(:record) { seller }
end
end
describe "GET show" do
include_context "with user signed in as admin for seller"
before do
seller.check_merchant_account_is_linked = true
seller.save!
end
it "returns http success and renders Inertia component" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq("Settings/Payments/Show")
settings_presenter = SettingsPresenter.new(pundit_user: controller.pundit_user)
expected_props = settings_presenter.payments_props(remote_ip: request.remote_ip)
# Compare only the expected props from inertia.props (ignore shared props)
actual_props = inertia.props.slice(*expected_props.keys)
# Convert actual countries hash keys from symbols to strings to match presenter output
# Inertia RSpec helper returns symbol keys, but presenter uses string keys
actual_props[:countries] = actual_props[:countries].transform_keys(&:to_s) if actual_props[:countries] && actual_props[:countries].keys.first.is_a?(Symbol)
expect(actual_props).to eq(expected_props)
end
end
describe "PUT update" do
let(:user) { seller }
before do
create(:user_compliance_info_empty, country: "United States", user:)
end
let(:params) do
{
first_name: "barnabas",
last_name: "barnabastein",
street_address: "123 barnabas st",
city: "barnabasville",
state: "NY",
zip_code: "94104",
dba: "barnie",
is_business: "off",
ssn_last_four: "6789",
dob_month: "3",
dob_day: "4",
dob_year: "1955",
phone: "+1#{GUMROAD_MERCHANT_DESCRIPTOR_PHONE_NUMBER.tr("()-", "")}",
}
end
let!(:request_1) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::LegalEntity::Address::STREET) }
let!(:request_2) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Business::Address::STREET) }
let!(:request_3) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Individual::Address::STREET) }
let!(:request_4) { create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::Business::TAX_ID) }
before do
allow(StripeMerchantAccountManager).to receive(:handle_new_user_compliance_info).and_return(true)
end
def expect_save_success_flash_message
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
describe "tos" do
describe "with terms notice displayed" do
describe "with time" do
let(:time_freeze) { Time.zone.local(2015, 4, 1) }
it "updates the tos last agreed at" do
travel_to(time_freeze) do
put :update, params: { user: params, terms_accepted: true }
end
user.reload
expect(user.tos_agreements.last.created_at).to eq(time_freeze)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
end
describe "with ip" do
let(:ip) { "54.234.242.13" }
before do
@request.remote_ip = ip
end
it "updates the tos last agreed ip" do
put :update, params: { user: params, terms_accepted: true }
user.reload
expect(user.tos_agreements.last.ip).to eq(ip)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
end
end
end
it "updates payouts_paused_by_user" do
expect do
put :update, params: { payouts_paused_by_user: true }
end.to change { user.reload.payouts_paused_by_user }.from(false).to(true)
end
describe "minimum payout threshold" do
it "updates the payout threshold for valid amounts" do
expect do
put :update, params: { payout_threshold_cents: 2000 }
end.to change { user.reload.payout_threshold_cents.to_i }.from(1000).to(2000)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "returns an error for invalid amounts" do
put :update, params: { payout_threshold_cents: 500 }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("Your payout threshold must be greater than the minimum payout amount")
expect(user.reload.payout_threshold_cents).to eq(1000)
end
end
describe "payout frequency" do
it "updates the payout frequency for valid values" do
expect do
put :update, params: { payout_frequency: User::PayoutSchedule::MONTHLY }
end.to change { user.reload.payout_frequency }.from(User::PayoutSchedule::WEEKLY).to(User::PayoutSchedule::MONTHLY)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "returns an error for invalid values" do
put :update, params: { payout_frequency: "invalid" }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("Payout frequency must be daily, weekly, monthly, or quarterly")
expect(user.reload.payout_frequency).to eq(User::PayoutSchedule::WEEKLY)
end
end
describe "individual" do
let(:all_params) do { user: params }.merge!(
bank_account: {
type: AchAccount.name,
account_number: "000123456789",
account_number_confirmation: "000123456789",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
) end
it "updates the compliance information and return the proper response" do
put :update, params: all_params
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.phone).to eq "+1#{GUMROAD_MERCHANT_DESCRIPTOR_PHONE_NUMBER.tr("()-", "")}"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "does not overwrite information for steps that the ui did not provide" do
put :update, params: all_params
put :update, params: { user: { first_name: "newfirst", last_name: "newlast" } }
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "newfirst"
expect(compliance_info.last_name).to eq "newlast"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "does not overwrite information for steps that the ui did provide as blank" do
put :update, params: all_params
put :update, params: { user: { first_name: "newfirst", last_name: "newlast", individual_tax_id: "" } }
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "newfirst"
expect(compliance_info.last_name).to eq "newlast"
expect(compliance_info.individual_tax_id).to be_present
expect(compliance_info.individual_tax_id.decrypt(GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD"))).to be_present
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "clears only the requests that are present" do
put :update, params: all_params
put :update, params: { user: { first_name: "newfirst", last_name: "newlast" } }
request_1.reload
request_2.reload
request_3.reload
request_4.reload
expect(request_1.state).to eq("provided")
expect(request_2.state).to eq("requested")
expect(request_3.state).to eq("provided")
expect(request_4.state).to eq("requested")
end
describe "immediate stripe account creation" do
let(:all_params) { { user: params } }
describe "user has a bank account, and a merchant account already" do
before do
all_params.merge!(
bank_account: {
type: AchAccount.name,
account_number: "000123456789",
account_number_confirmation: "000123456789",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
)
create(:merchant_account, user:)
end
it "does not try to create a new stripe account because user already has one" do
expect(StripeMerchantAccountManager).not_to receive(:create_account)
put :update, params: all_params
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
end
describe "user does not have a bank account, or a merchant account" do
it "does not try to create a new stripe account because user does not have a bank account" do
expect(StripeMerchantAccountManager).not_to receive(:create_account)
put :update, params: all_params
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
end
describe "user has a bank account but not a merchant account" do
it "creates a new stripe merchant account for the user" do
all_params.merge!(
bank_account: {
type: AchAccount.name,
account_number: "000123456789",
account_number_confirmation: "000123456789",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
)
expect(StripeMerchantAccountManager).to receive(:create_account).with(user, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")).and_call_original
put :update, params: all_params
expect(user.reload.stripe_account).to be_present
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "raises error if stripe account creation fails" do
all_params.merge!(
bank_account: {
type: AchAccount.name,
account_number: "123123123",
account_number_confirmation: "123123123",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
)
expect(StripeMerchantAccountManager).to receive(:create_account).with(user, passphrase: GlobalConfig.get("STRONGBOX_GENERAL_PASSWORD")).and_call_original
put :update, params: all_params
expect(user.reload.stripe_account).to be_nil
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("You must use a test bank account number in test mode. Try 000123456789 or see more options at https://stripe.com/docs/connect/testing#account-numbers.")
end
end
end
describe "user enters a birthday accidentally that is under 13 years old given todays date" do
before do
put :update, params: { user: params }
params.merge!(
dob_month: "1",
dob_day: "1",
dob_year: Time.current.year.to_s
)
end
it "returns an error" do
put :update, params: { user: params }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("You must be 13 years old to use Gumroad.")
end
it "leaves the previous user compliance info data unchanged" do
old_user_compliance_info_id = user.alive_user_compliance_info.id
old_user_compliance_info_birthday = user.alive_user_compliance_info.birthday
put :update, params: { user: params }
expect(user.alive_user_compliance_info.id).to eq(old_user_compliance_info_id)
expect(user.alive_user_compliance_info.birthday).to eq(old_user_compliance_info_birthday)
end
end
describe "creator enters an invalid zip code" do
before do
params.merge!(
business_zip_code: "9410494104",
)
end
it "returns an error response" do
put :update, params: { user: params }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("You entered a ZIP Code that doesn't exist within your country.")
end
end
describe "user is verified" do
before do
put :update, params: { user: params }
user.merchant_accounts << create(:merchant_account, charge_processor_verified_at: Time.current)
end
describe "user saves existing data unchanged" do
before do
put :update, params: { user: params }
end
it "returns success" do
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "the users current compliance info should contain the same data" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
end
end
describe "user wishes to edit a frozen field (e.g. first name)" do
before do
error_message = "Invalid request: You cannot change legal_entity[first_name] via API if an account is verified."
allow(StripeMerchantAccountManager).to receive(:handle_new_user_compliance_info).and_raise(Stripe::InvalidRequestError.new(error_message, nil))
params.merge!(first_name: "barny")
put :update, params: { user: params }
end
it "returns an error" do
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to be_present
end
it "the users current compliance info should be changed" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barny"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
end
end
describe "user wishes to edit a frozen field (e.g. dob that may be edited if nil)" do
let(:params) do
{
first_name: "barnabas",
last_name: "barnabastein",
street_address: "123 barnabas st",
city: "barnabasville",
state: "NY",
zip_code: "94104",
dba: "barnie",
is_business: "off",
ssn_last_four: "6789"
}
end
before do
params.merge!(dob_month: "02", dob_day: "01", dob_year: "1980")
put :update, params: { user: params }
end
it "returns success" do
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "the users current compliance info should be changed" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
expect(compliance_info.birthday).to eq(Date.new(1980, 2, 1))
end
end
describe "user wishes to edit a non-frozen feild (e.g. address)" do
before do
params.merge!(street_address: "124 Barnabas St")
put :update, params: { user: params }
end
it "returns success" do
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "the users current compliance info should contain the new address" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "124 Barnabas St"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
end
end
it "allows the user to change the account type from individual to business" do
# Save the account type as "individual"
put :update, params: { user: params }
# Then try to switch to the "business" account type
params.merge!(
is_business: "on",
business_street_address: "123 main street",
business_city: "sf",
business_state: "CA",
business_zip_code: "94107",
business_type: UserComplianceInfo::BusinessTypes::LLC,
business_tax_id: "123-123-123"
)
put :update, params: { user: params }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
compliance_info = user.alive_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
expect(compliance_info.is_business).to be(true)
expect(compliance_info.business_street_address).to eq "123 main street"
expect(compliance_info.business_city).to eq "sf"
expect(compliance_info.business_state).to eq "CA"
expect(compliance_info.business_zip_code).to eq "94107"
expect(compliance_info.business_type).to eq "llc"
expect(compliance_info.business_tax_id.decrypt("1234")).to eq "123-123-123"
end
end
describe "user is verified, and their compliance info was old and is_business=nil when we created their merchant account" do
before do
params.merge!(
is_business: nil
)
put :update, params: { user: params }
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.is_business).to be(nil)
user.merchant_accounts << create(:merchant_account, charge_processor_verified_at: Time.current)
end
describe "user submits their compliance info, and the new form submits is_business=off" do
before do
params.merge!(
is_business: "off"
)
put :update, params: { user: params }
end
it "returns success" do
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "the users current compliance info should contain the same details" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
end
it "the users current compliance info should contain is_business=false" do
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.is_business).to be(false)
end
end
end
end
describe "business" do
let(:business_params) do
params.merge(
is_business: "on",
business_street_address: "123 main street",
business_city: "sf",
business_state: "CA",
business_zip_code: "94107",
business_type: UserComplianceInfo::BusinessTypes::LLC,
business_tax_id: "123-123-123"
)
end
it "updates the compliance information and return the proper response" do
put :update, params: { user: business_params }
compliance_info = user.fetch_or_build_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
expect(compliance_info.is_business).to be(true)
expect(compliance_info.business_street_address).to eq "123 main street"
expect(compliance_info.business_city).to eq "sf"
expect(compliance_info.business_state).to eq "CA"
expect(compliance_info.business_zip_code).to eq "94107"
expect(compliance_info.business_type).to eq "llc"
expect(compliance_info.business_tax_id.decrypt("1234")).to eq "123-123-123"
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
end
it "clears the requests that are present" do
put :update, params: { user: business_params }
request_1.reload
request_2.reload
request_3.reload
request_4.reload
expect(request_1.state).to eq("provided")
expect(request_2.state).to eq("provided")
expect(request_3.state).to eq("provided")
expect(request_4.state).to eq("provided")
end
it "allows the user to change the account type from business to individual after verification" do
# Save the account type as "business" and mark verified
put :update, params: { user: business_params }
user.merchant_accounts << create(:merchant_account, charge_processor_verified_at: Time.current)
# Then try to switch to the "individual" account type
business_params.merge!(is_business: "off")
put :update, params: { user: business_params }
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :see_other
expect(flash[:notice]).to eq("Thanks! You're all set.")
compliance_info = user.alive_user_compliance_info
expect(compliance_info.first_name).to eq "barnabas"
expect(compliance_info.last_name).to eq "barnabastein"
expect(compliance_info.street_address).to eq "123 barnabas st"
expect(compliance_info.city).to eq "barnabasville"
expect(compliance_info.state).to eq "NY"
expect(compliance_info.zip_code).to eq "94104"
expect(compliance_info.is_business).to be(false)
expect(compliance_info.individual_tax_id.decrypt("1234")).to eq "6789"
expect(compliance_info.business_street_address).to eq "123 main street"
expect(compliance_info.business_city).to eq "sf"
expect(compliance_info.business_state).to eq "CA"
expect(compliance_info.business_zip_code).to eq "94107"
expect(compliance_info.business_type).to eq "llc"
expect(compliance_info.business_tax_id.decrypt("1234")).to eq "123-123-123"
end
end
describe "ach account" do
let(:user) { create(:user) }
before do
sign_in user
end
describe "success" do
let(:params) do
{
bank_account: {
type: AchAccount.name,
account_number: "000123456789",
account_number_confirmation: "000123456789",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
}
end
let(:request) do
create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::BANK_ACCOUNT)
end
before do
request
end
it "creates the ach account" do
put(:update, params:)
bank_account = AchAccount.last
expect(bank_account.account_number.decrypt("1234")).to eq "000123456789"
expect(bank_account.account_number_last_four).to eq "6789"
expect(bank_account.routing_number).to eq "110000000"
expect(bank_account.account_holder_full_name).to eq "gumbot"
expect(bank_account.account_type).to eq "checking"
end
it "clears the request for the bank account" do
put(:update, params:)
request.reload
expect(request.state).to eq("provided")
end
context "with invalid bank code" do
before do
params[:bank_account][:type] = "SingaporeanBankAccount"
params[:bank_account][:bank_code] = "BKCH"
end
it "returns error" do
put(:update, params:)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("The bank code is invalid. and The branch code is invalid.")
end
end
end
describe "success with dashes/hyphens and leading/trailing spaces" do
let(:params) do
{
bank_account: {
type: AchAccount.name,
account_number: " 000-1234-56789 ",
account_number_confirmation: " 000-1234-56789 ",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
}
end
let(:request) do
create(:user_compliance_info_request, user:, field_needed: UserComplianceInfoFields::BANK_ACCOUNT)
end
before do
request
end
it "creates the ach account" do
put(:update, params:)
bank_account = AchAccount.last
expect(bank_account.account_number.decrypt("1234")).to eq "000123456789"
expect(bank_account.account_number_last_four).to eq "6789"
expect(bank_account.routing_number).to eq "110000000"
expect(bank_account.account_holder_full_name).to eq "gumbot"
expect(bank_account.account_type).to eq "checking"
end
it "clears the request for the bank account" do
put(:update, params:)
request.reload
expect(request.state).to eq("provided")
end
end
describe "account number and repeated account number don't match" do
let(:params) do
{
bank_account: {
type: AchAccount.name,
account_number: "123123123",
account_number_confirmation: "222222222",
routing_number: "110000000",
account_holder_full_name: "gumbot"
}
}
end
let(:request) do
create(:user_compliance_info_request, field_needed: UserComplianceInfoFields::BANK_ACCOUNT)
end
before do
request
end
it "fails if the account numbers don't match" do
put(:update, params:)
expect(response).to redirect_to(settings_payments_path)
expect(response).to have_http_status :found
expect(session[:inertia_errors][:base]).to include("The account numbers do not match.")
end
it "does not clear the request for the bank account" do
put(:update, params:)
request.reload
expect(request.state).to eq("requested")
end
end
describe "canadian bank account" do
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | true |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/team/invitations_controller_spec.rb | spec/controllers/settings/team/invitations_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe Settings::Team::InvitationsController 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) { Settings::Team::TeamInvitationPolicy }
let(:record) { TeamInvitation }
let(:request_params) { { email: "", role: nil } }
let(:request_format) { :json }
end
context "when payload is valid" do
it "creates team invitation record" do
allow(TeamMailer).to receive(:invite).and_call_original
expect do
post :create, params: { team_invitation: { email: "member@example.com", role: "admin" } }, as: :json
end.to change { seller.team_invitations.count }.by(1)
expect(TeamMailer).to have_received(:invite).with(TeamInvitation.last)
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
team_invitation = seller.team_invitations.last
expect(team_invitation.email).to eq("member@example.com")
expect(team_invitation.role_admin?).to eq(true)
expect(team_invitation.expires_at).not_to be(nil)
end
end
context "when payload is not valid" do
it "returns error" do
allow(TeamMailer).to receive(:invite)
expect do
post :create, params: { team_invitation: { email: "", role: "" } }, as: :json
end.not_to change { seller.team_invitations.count }
expect(TeamMailer).not_to have_received(:invite)
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error_message"]).to eq("Email is invalid and Role is not included in the list")
end
end
end
describe "PUT update" do
let(:team_invitation) { create(:team_invitation, seller:, role: TeamMembership::ROLE_MARKETING) }
it_behaves_like "authorize called for action", :put, :update do
let(:policy_klass) { Settings::Team::TeamInvitationPolicy }
let(:record) { team_invitation }
let(:request_params) { { id: team_invitation.external_id, team_invitation: { role: TeamMembership::ROLE_ADMIN } } }
let(:request_format) { :json }
end
it "updates role" do
put :update, params: { id: team_invitation.external_id, team_invitation: { role: TeamMembership::ROLE_ADMIN } }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_invitation.reload.role_admin?).to eq(true)
end
end
describe "DELETE destroy" do
let(:team_invitation) { create(:team_invitation, seller:) }
it_behaves_like "authorize called for action", :delete, :destroy do
let(:policy_klass) { Settings::Team::TeamInvitationPolicy }
let(:record) { team_invitation }
let(:request_format) { :json }
let(:request_params) { { id: team_invitation.external_id } }
end
it "updates record as deleted" do
delete :destroy, params: { id: team_invitation.external_id }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_invitation.reload.deleted?).to eq(true)
end
context "with record belonging to other seller" do
let(:team_invitation) { create(:team_invitation) }
it "returns 404" do
delete :destroy, params: { id: team_invitation.external_id }, as: :json
expect_404_response(response)
end
end
end
describe "PUT restore" do
let(:team_invitation) { create(:team_invitation, seller:) }
before do
team_invitation.update_as_deleted!
end
it_behaves_like "authorize called for action", :put, :restore do
let(:policy_klass) { Settings::Team::TeamInvitationPolicy }
let(:record) { team_invitation }
let(:request_format) { :json }
let(:request_params) { { id: team_invitation.external_id } }
end
it "updates record as deleted" do
put :restore, params: { id: team_invitation.external_id }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_invitation.reload.deleted?).to eq(false)
end
context "with record belonging to other seller" do
let(:team_invitation) { create(:team_invitation) }
it "returns 404" do
put :restore, params: { id: team_invitation.external_id }, as: :json
expect_404_response(response)
end
end
end
describe "GET accept" do
let(:email) { "Member@example.com" }
let(:user) { create(:named_user, email:) }
let(:team_invitation) { create(:team_invitation, seller:, email: user.email) }
before do
sign_in(user)
end
it_behaves_like "authorize called for action", :get, :accept do
let(:policy_klass) { Settings::Team::TeamInvitationPolicy }
let(:record) { team_invitation }
let(:request_params) { { id: team_invitation.external_id } }
end
it "successfully accepts the invitation" do
allow(TeamMailer).to receive(:invitation_accepted).and_call_original
expect do
get :accept, params: { id: team_invitation.external_id }
end.to change { seller.seller_memberships.count }
expect(team_invitation.reload.accepted?).to eq(true)
expect(team_invitation.deleted?).to eq(true)
expect(user.user_memberships.count).to eq(2)
owner_membership = user.user_memberships.first
expect(owner_membership.role).to eq(TeamMembership::ROLE_OWNER)
seller_membership = user.user_memberships.last
expect(user.reload.is_team_member).to eq(false)
expect(seller_membership.role).to eq(team_invitation.role)
expect(TeamMailer).to have_received(:invitation_accepted).with(TeamMembership.last)
expect(cookies.encrypted[:current_seller_id]). to eq(seller.id)
expect(response).to redirect_to(dashboard_url)
expect(flash[:notice]).to eq("Welcome to the team at seller!")
end
context "when the seller is Gumroad" do
let(:seller) { create(:named_seller, email: ApplicationMailer::ADMIN_EMAIL) }
before { team_invitation.update!(seller:) }
it "sets the user's is_team_member flag to true" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.to change { seller.seller_memberships.count }
expect(user.reload.is_team_member).to eq(true)
end
end
context "when logged-in user email is missing" do
let(:team_invitation) { create(:team_invitation, seller:, email:) }
before do
user.update_attribute(:email, nil)
end
it "renders email missing alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Your Gumroad account doesn't have an email associated. Please assign and verify your email before accepting the invitation.")
end
end
context "when logged-in user email is not confirmed" do
before { user.update!(confirmed_at: nil) }
it "renders unconfirmed email alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Please confirm your email address before accepting the invitation.")
end
end
context "when logged-in user email is different" do
before { team_invitation.update!(email: "wrong.email@example.com") }
it "renders email mismatch alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("The invite was sent to a different email address. You are logged in as member@example.com")
end
end
context "when invitation has expired" do
before { team_invitation.update!(expires_at: 1.second.ago) }
it "renders expired invitation alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Invitation link has expired. Please contact the account owner.")
end
end
context "when the invitation has already been accepted" do
before { team_invitation.update_as_accepted! }
it "renders invitation already accepted alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Invitation has already been accepted.")
end
end
context "when the invitation has been deleted" do
before { team_invitation.update_as_deleted! }
it "renders invitation already accepted alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Invitation link is invalid. Please contact the account owner.")
end
end
context "when the invitation email matches the owner's email" do
before do
# Edge case when the seller changes their email to the same email used for the invitation
team_invitation.update_attribute(:email, seller.email)
sign_in(seller)
end
it "deletes the invitation and renders invitation invalid alert" do
expect do
get :accept, params: { id: team_invitation.external_id }
end.not_to change { seller.seller_memberships.count }
expect(team_invitation.reload.deleted?).to eq(true)
expect(response).to redirect_to(dashboard_url)
expect(flash[:alert]).to eq("Invitation link is invalid. Please contact the account owner.")
end
end
end
describe "PUT resend_invitation" do
let(:team_invitation) { create(:team_invitation, seller:, expires_at: 1.year.ago) }
it_behaves_like "authorize called for action", :put, :resend_invitation do
let(:policy_klass) { Settings::Team::TeamInvitationPolicy }
let(:record) { team_invitation }
let(:request_format) { :json }
let(:request_params) { { id: team_invitation.external_id } }
end
it "updates team invitation record and enqueues email" do
allow(TeamMailer).to receive(:invite).and_call_original
put :resend_invitation, params: { id: team_invitation.external_id }, as: :json
expect(TeamMailer).to have_received(:invite).with(team_invitation)
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_invitation.reload.expires_at).to be_within(1.second).of(
TeamInvitation::ACTIVE_INTERVAL_IN_DAYS.days.from_now.at_end_of_day
)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/settings/team/members_controller_spec.rb | spec/controllers/settings/team/members_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/sellers_base_controller_concern"
require "shared_examples/authorize_called"
describe Settings::Team::MembersController do
it_behaves_like "inherits from Sellers::BaseController"
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(:policy_klass) { Settings::Team::UserPolicy }
let(:policy_method) { :show? }
let(:record) { seller }
let(:request_format) { :json }
end
it "returns http success and assigns correct instance variables" do
get :index, as: :json
expect(response).to be_successful
team_presenter = assigns[:team_presenter]
expect(team_presenter.pundit_user).to eq(controller.pundit_user)
expect(response.parsed_body["success"]).to eq(true)
member_infos = team_presenter.member_infos.map(&:to_hash).map(&:stringify_keys!)
member_infos.each do |member_info|
member_info["options"].map(&:to_hash).map(&:stringify_keys!)
member_info["leave_team_option"]&.stringify_keys!
end
expect(response.parsed_body["member_infos"]).to eq(member_infos)
end
end
describe "PUT update" do
let(:team_membership) { create(:team_membership, seller:, role: TeamMembership::ROLE_MARKETING) }
it_behaves_like "authorize called for action", :put, :update do
let(:policy_klass) { Settings::Team::TeamMembershipPolicy }
let(:record) { team_membership }
let(:request_params) { { id: team_membership.external_id, team_membership: { role: TeamMembership::ROLE_ADMIN } } }
let(:request_format) { :json }
end
it "updates role" do
put :update, params: { id: team_membership.external_id, team_membership: { role: TeamMembership::ROLE_ADMIN } }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_membership.reload.role_admin?).to eq(true)
end
end
describe "DELETE destroy" do
let(:user) { create(:user, is_team_member: true) }
let(:team_membership) { create(:team_membership, seller:, user:) }
it_behaves_like "authorize called for action", :delete, :destroy do
let(:policy_klass) { Settings::Team::TeamMembershipPolicy }
let(:record) { team_membership }
let(:request_format) { :json }
let(:request_params) { { id: team_membership.external_id } }
end
it "marks record as deleted" do
delete :destroy, params: { id: team_membership.external_id }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(user.reload.is_team_member).to eq(true)
expect(team_membership.reload.deleted?).to eq(true)
end
context "with record belonging to other seller" do
let(:team_membership) { create(:team_membership) }
it "returns 404" do
delete :destroy, params: { id: team_membership.external_id }, as: :json
expect_404_response(response)
end
end
context "when the seller is Gumroad" do
let(:seller) { create(:named_seller, email: ApplicationMailer::ADMIN_EMAIL) }
let(:team_membership) { create(:team_membership, seller:, user:) }
it "removes the is_team_member flag from the user" do
delete :destroy, params: { id: team_membership.external_id }, as: :json
expect(user.reload.is_team_member).to eq(false)
end
end
end
describe "PATCH restore" do
let(:team_membership) { create(:team_membership, seller:) }
before do
team_membership.update_as_deleted!
end
it_behaves_like "authorize called for action", :put, :restore do
let(:policy_klass) { Settings::Team::TeamMembershipPolicy }
let(:record) { team_membership }
let(:request_format) { :json }
let(:request_params) { { id: team_membership.external_id } }
end
it "marks record as not deleted" do
put :restore, params: { id: team_membership.external_id }, as: :json
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(team_membership.reload.deleted?).to eq(false)
end
context "with record belonging to other seller" do
let(:team_membership) { create(:team_membership) }
it "returns 404" do
put :restore, params: { id: team_membership.external_id }, as: :json
expect_404_response(response)
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/settings/profile/products_controller_spec.rb | spec/controllers/settings/profile/products_controller_spec.rb | # frozen_string_literal: true
require "shared_examples/authorize_called"
describe Settings::Profile::ProductsController do
let(:seller) { create(:user) }
let(:product) { create(:product, user: seller) }
include_context "with user signed in as admin for seller"
describe "GET show" do
it_behaves_like "authorize called for action", :get, :show do
let!(:record) { product }
let(:policy_klass) { LinkPolicy }
let(:request_params) { { id: product.external_id } }
end
it "returns props for that product" do
get :show, params: { id: product.external_id }
expect(response).to be_successful
expect(response.parsed_body).to eq(ProductPresenter.new(product:, request:).product_props(seller_custom_domain_url: nil).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/stripe/setup_intents_controller_spec.rb | spec/controllers/stripe/setup_intents_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Stripe::SetupIntentsController, :vcr do
describe "POST create" do
context "when card params are invalid" do
it "responds with an error" do
post :create, params: {}
expect(response).to be_unprocessable
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error_message"]).to eq("We couldn't charge your card. Try again or use a different card.")
end
end
context "when card handling error occurred" do
it "responds with an error" do
post :create, params: StripePaymentMethodHelper.decline.to_stripejs_params
expect(response).to be_unprocessable
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error_message"]).to eq("Your card was declined.")
end
end
context "when card params are valid" do
let(:card_with_sca) { StripePaymentMethodHelper.success_indian_card_mandate }
it "creates a Stripe customer and sets up future usage" do
expect(Stripe::Customer).to receive(:create).with(hash_including(payment_method: card_with_sca.to_stripejs_payment_method_id)).and_call_original
expect(ChargeProcessor).to receive(:setup_future_charges!).with(anything, anything, mandate_options: {
payment_method_options: {
card: {
mandate_options: hash_including({
amount_type: "maximum",
amount: 10_00,
currency: "usd",
interval: "sporadic",
supported_types: ["india"]
})
}
}
}).and_call_original
post :create, params: card_with_sca.to_stripejs_params.merge!(products: [{ price: 10_00 }, { price: 5_00 }, { price: 7_00 }])
end
context "when setup intent succeeds" do
it "renders a successful response" do
post :create, params: StripePaymentMethodHelper.success_with_sca.to_stripejs_params
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["reusable_token"]).to be_present
expect(response.parsed_body["setup_intent_id"]).to be_present
end
end
context "when setup intent requires action" do
it "renders a successful response" do
post :create, params: StripePaymentMethodHelper.success_with_sca.to_stripejs_params
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["requires_card_setup"]).to eq(true)
expect(response.parsed_body["reusable_token"]).to be_present
expect(response.parsed_body["client_secret"]).to be_present
expect(response.parsed_body["setup_intent_id"]).to be_present
end
end
context "when charge processor error occurs" do
before do
allow(ChargeProcessor).to receive(:setup_future_charges!).and_raise(ChargeProcessorUnavailableError)
end
it "responds with an error" do
post :create, params: StripePaymentMethodHelper.success_with_sca.to_stripejs_params
expect(response).to be_server_error
expect(response.parsed_body["success"]).to eq(false)
expect(response.parsed_body["error_message"]).to eq("There is a temporary problem, please try again (your card was not charged).")
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/admin/suspend_users_controller_spec.rb | spec/controllers/admin/suspend_users_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::SuspendUsersController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before(:each) do
sign_in admin_user
end
describe "GET show" do
it "renders the page" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq "Admin/SuspendUsers/Show"
expect(inertia.props[:title]).to eq("Mass-suspend users")
expect(inertia.props[:suspend_reasons]).to eq([
"Violating our terms of service",
"Creating products that violate our ToS",
"Using Gumroad to commit fraud",
"Using Gumroad for posting spam or SEO manipulation",
])
expect(inertia.props[:authenticity_token]).to be_present
end
end
describe "PUT update" do
let(:users_to_suspend) { create_list(:user, 2) }
let(:user_ids_to_suspend) { users_to_suspend.map { |user| user.id.to_s } }
let(:reason) { "Violating our terms of service" }
let(:additional_notes) { nil }
before do
put :update, params: { suspend_users: { identifiers: specified_ids, reason:, additional_notes: } }
end
context "when the specified users IDs are separated by newlines" do
let(:specified_ids) { user_ids_to_suspend.join("\n") }
it "enqueues a job to suspend the specified users" do
expect(SuspendUsersWorker).to have_enqueued_sidekiq_job(admin_user.id, user_ids_to_suspend, reason, additional_notes)
expect(flash[:notice]).to eq "User suspension in progress!"
expect(response).to redirect_to(admin_suspend_users_url)
end
end
context "when the specified users IDs are separated by commas" do
let(:specified_ids) { user_ids_to_suspend.join(", ") }
it "enqueues a job to suspend the specified users" do
expect(SuspendUsersWorker).to have_enqueued_sidekiq_job(admin_user.id, user_ids_to_suspend, reason, additional_notes)
expect(flash[:notice]).to eq "User suspension in progress!"
expect(response).to redirect_to(admin_suspend_users_url)
end
end
context "when external IDs are provided" do
let(:external_ids_to_suspend) { users_to_suspend.map(&:external_id) }
let(:specified_ids) { external_ids_to_suspend.join(", ") }
it "enqueues a job to suspend the specified users" do
expect(SuspendUsersWorker).to have_enqueued_sidekiq_job(admin_user.id, external_ids_to_suspend, reason, additional_notes)
expect(flash[:notice]).to eq "User suspension in progress!"
expect(response).to redirect_to(admin_suspend_users_url)
end
end
context "when additional notes are provided" do
let(:additional_notes) { "Some additional notes" }
let(:specified_ids) { user_ids_to_suspend.join(", ") }
it "passes the additional notes as job's param" do
expect(SuspendUsersWorker).to have_enqueued_sidekiq_job(admin_user.id, user_ids_to_suspend, reason, additional_notes)
expect(flash[:notice]).to eq "User suspension in progress!"
expect(response).to redirect_to(admin_suspend_users_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/admin/merchant_accounts_controller_spec.rb | spec/controllers/admin/merchant_accounts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::MerchantAccountsController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET show" do
let(:merchant_account) { create(:merchant_account) }
before do
allow(Stripe::Account).to receive(:retrieve).and_return(double(:account, charges_enabled: true, payouts_enabled: true, requirements: double(:requirements, disabled_reason: nil, as_json: {})))
end
it "redirects numeric ID to external_id" do
get :show, params: { external_id: merchant_account.id }
expect(response).to redirect_to admin_merchant_account_path(merchant_account.external_id)
end
it "renders the page successfully with external_id" do
get :show, params: { external_id: merchant_account.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/MerchantAccounts/Show")
end
it "renders the page successfully with charge_processor_merchant_id" do
get :show, params: { external_id: merchant_account.charge_processor_merchant_id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/MerchantAccounts/Show")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/base_controller_spec.rb | spec/controllers/admin/base_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "inertia_rails/rspec"
describe Admin::BaseController, type: :controller, inertia: true do
render_views
class DummyPolicy < ApplicationPolicy
def index_with_policy?
false
end
end
controller(Admin::BaseController) do
def index_with_policy
authorize :dummy
render json: { success: true }
end
end
before do
routes.draw do
namespace :admin do
get :index, to: "base#index"
get :index_with_policy, to: "base#index_with_policy"
get :redirect_to_stripe_dashboard, to: "base#redirect_to_stripe_dashboard"
end
end
end
let(:admin_user) { create(:admin_user) }
describe "require_admin!" do
shared_examples_for "404 for xhr request" do
it do
get :index, xhr: true
expect_404_response(response)
end
end
shared_examples_for "404 for json request format" do
it do
get :index, format: :json
expect_404_response(response)
end
end
context "when not logged in" do
it_behaves_like "404 for xhr request"
it_behaves_like "404 for json request format"
context "with html request format" do
before do
@request.path = "/about"
end
it "redirects user to login when trying to access admin with proper next param value" do
get :index
expect(response).to redirect_to(login_path(next: "/about"))
end
end
end
context "when logged in" do
let(:not_admin_user) { create(:user) }
context "with non-admin as current user" do
before do
sign_in not_admin_user
end
context "with self as current seller" do
# current_seller = logged_in_user for user without team_memberhip
it_behaves_like "404 for xhr request"
it_behaves_like "404 for json request format"
context "with html request format" do
it "redirects to root_path and does not add next param" do
get :index
expect(response).to redirect_to(root_path)
end
end
end
context "with admin as current seller" do
before do
allow_any_instance_of(ApplicationController).to receive(:current_seller).and_return(admin_user)
end
it_behaves_like "404 for xhr request"
it_behaves_like "404 for json request format"
context "with html request format" do
it "redirects to root_path and does not add next param" do
get :index
expect(response).to redirect_to(root_path)
end
end
end
end
context "with admin as current user" do
before do
sign_in admin_user
end
context "with self as current seller" do
# current_seller = logged_in_user for user without team_memberhip
it "returns the desired response" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq "Admin/Base/Index"
expect(inertia.props[:title]).to eq("Admin")
end
end
context "with non-admin as current seller" do
it "returns the desired response" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq "Admin/Base/Index"
expect(inertia.props[:title]).to eq("Admin")
end
end
end
end
end
describe "user_not_authorized" do
before do
sign_in admin_user
end
context "with JSON request" do
it "renders JSON response" do
get :index_with_policy, format: :json
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 "with JS request" do
it "renders JSON response" do
get :index_with_policy, xhr: 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 "with non-JSON request" do
it "redirects" do
get :index_with_policy
expect(response).to redirect_to "/"
expect(flash[:alert]).to eq("You are not allowed to perform this action.")
end
end
end
describe "GET redirect_to_stripe_dashboard" do
before do
sign_in admin_user
end
context "when the seller has a Stripe account" do
let(:seller) { create(:user) }
let!(:merchant_account) { create(:merchant_account, user: seller) }
it "redirects to Stripe dashboard" do
get :redirect_to_stripe_dashboard, params: { user_identifier: seller.email }
expect(response).to redirect_to(
"https://dashboard.stripe.com/test/connect/accounts/#{merchant_account.charge_processor_merchant_id}"
)
end
end
context "when the seller is not found" do
it "redirects to admin path with error" do
get :redirect_to_stripe_dashboard, params: { user_identifier: "nonexistent@example.com" }
expect(response).to redirect_to(admin_path)
expect(flash[:alert]).to eq("User not found")
end
end
context "when user has no Stripe account" do
let(:user) { create(:user) }
it "redirects to admin path with error" do
get :redirect_to_stripe_dashboard, params: { user_identifier: user.email }
expect(response).to redirect_to(admin_path)
expect(flash[:alert]).to eq("Stripe account not found")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/refund_queues_controller_spec.rb | spec/controllers/admin/refund_queues_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::RefundQueuesController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user_1) { create(:user, created_at: 1.day.ago, updated_at: 1.day.ago) }
let(:user_2) { create(:user, created_at: 2.days.ago, updated_at: 2.days.ago) }
let(:user_3) { create(:user, created_at: 3.days.ago, updated_at: 3.days.ago) }
let(:users) do
User.where(id: [user_1.id, user_2.id, user_3.id]).order(updated_at: :desc, id: :desc)
end
before(:each) do
sign_in admin_user
end
describe "GET show" do
before do
allow(User).to receive(:refund_queue).and_return(users)
end
it "renders the page" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq "Admin/RefundQueues/Show"
props = inertia.props
expect(props[:title]).to eq("Refund queue")
expect(props[:users]).to match_array([
hash_including(id: user_1.id),
hash_including(id: user_2.id),
hash_including(id: user_3.id)
])
end
it "renders the page with pagination" do
get :show, params: { page: 2, per_page: 2 }
expect(response).to be_successful
expect(inertia.component).to eq "Admin/RefundQueues/Show"
props = inertia.props
expect(props[:pagination]).to be_present
expect(props[:users]).to contain_exactly(hash_including(id: user_3.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/admin/users_controller_spec.rb | spec/controllers/admin/users_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::UsersController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
before do
@admin_user = create(:admin_user)
sign_in @admin_user
end
describe "GET 'verify'" do
before do
@user = create(:user)
@product = create(:product, user: @user)
@purchases = []
5.times do
@purchases << create(:purchase, link: @product, seller: @product.user, stripe_transaction_id: rand(9_999))
end
@params = { id: @user.id }
end
it "successfully verifies and unverifies users" do
expect(@user.verified.nil?).to be(true)
get :verify, params: @params
expect(response.parsed_body["success"]).to be(true)
expect(@user.reload.verified).to be(true)
get :verify, params: @params
expect(response.parsed_body["success"]).to be(true)
expect(@user.reload.verified).to be(false)
end
context "when error is raised" do
before do
allow_any_instance_of(User).to receive(:save!).and_raise("Error!")
end
it "rescues and returns error message" do
get :verify, params: @params
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to eq("Error!")
end
end
end
describe "GET 'show'" do
let(:user) { create(:user) }
it "returns page successfully" do
get "show", params: { id: user.id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Users/Show")
expect(inertia.props[:user][:id]).to eq(user.id)
end
it "returns page successfully when using email" do
get "show", params: { id: user.email }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Users/Show")
expect(inertia.props[:user][:id]).to eq(user.id)
end
end
describe "refund balance logic", :vcr, :sidekiq_inline do
describe "POST 'refund_balance'" do
before do
@admin_user = create(:admin_user)
sign_in @admin_user
@user = create(:user)
product = create(:product, user: @user)
@purchase = create(:purchase, link: product, purchase_state: "in_progress", chargeable: create(:chargeable))
@purchase.process!
@purchase.increment_sellers_balance!
@purchase.mark_successful!
end
it "refunds user's purchases if the user is suspended" do
@user.flag_for_fraud(author_id: @admin_user.id)
@user.suspend_for_fraud(author_id: @admin_user.id)
post :refund_balance, params: { id: @user.id }
expect(@purchase.reload.stripe_refunded).to be(true)
end
it "does not refund user's purchases if the user is not suspended" do
post :refund_balance, params: { id: @user.id }
expect(@purchase.reload.stripe_refunded).to_not be(true)
end
end
end
describe "POST 'add_credit'" do
before do
@user = create(:user)
@params = { id: @user.id,
credit: {
credit_amount: "100"
} }
end
it "successfully creates a credit" do
expect { post :add_credit, params: @params }.to change { Credit.count }.from(0).to(1)
expect(Credit.last.amount_cents).to eq(10_000)
expect(Credit.last.user).to eq(@user)
end
it "creates a credit always associated with a gumroad merchant account" do
create(:merchant_account, user: @user)
@user.reload
post :add_credit, params: @params
expect(Credit.last.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id))
expect(Credit.last.balance.merchant_account).to eq(MerchantAccount.gumroad(StripeChargeProcessor.charge_processor_id))
end
it "successfully creates credits even with smaller amounts" do
@params = { id: @user.id,
credit: {
credit_amount: ".04"
} }
expect { post :add_credit, params: @params }.to change { Credit.count }.from(0).to(1)
expect(Credit.last.amount_cents).to eq(4)
expect(Credit.last.user).to eq(@user)
end
it "sends notification to user" do
@params = { id: @user.id,
credit: {
credit_amount: ".04"
} }
mail_double = double
allow(mail_double).to receive(:deliver_later)
expect(ContactingCreatorMailer).to receive(:credit_notification).with(@user.id, 4).and_return(mail_double)
post :add_credit, params: @params
end
end
describe "POST #mark_compliant" do
let(:user) { create(:user) }
it "marks the user as compliant" do
post :mark_compliant, params: { id: user.id }
expect(response).to be_successful
expect(user.reload.user_risk_state).to eq "compliant"
end
it "creates a comment when marking compliant" do
freeze_time do
expect do
post :mark_compliant, params: { id: user.id }
end.to change(user.comments, :count).by(1)
comment = user.comments.last
expect(comment).to have_attributes(
comment_type: Comment::COMMENT_TYPE_COMPLIANT,
content: "Marked compliant by #{@admin_user.username} on #{Time.current.strftime('%B %-d, %Y')}",
author: @admin_user
)
end
end
end
describe "POST #set_custom_fee" do
let(:user) { create(:user) }
it "sets the custom fee for the user" do
post :set_custom_fee, params: { id: user.id, custom_fee_percent: "2.5" }
expect(response).to be_successful
expect(user.reload.custom_fee_per_thousand).to eq 25
end
it "returns error if custom fee parameter is invalid" do
post :set_custom_fee, params: { id: user.id, custom_fee_percent: "-5" }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to eq("Validation failed: Custom fee per thousand must be greater than or equal to 0")
expect(user.reload.custom_fee_per_thousand).to be_nil
post :set_custom_fee, params: { id: user.id, custom_fee_percent: "101" }
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to eq("Validation failed: Custom fee per thousand must be less than or equal to 1000")
expect(user.reload.custom_fee_per_thousand).to be_nil
end
it "updates the existing custom fee" do
user.update!(custom_fee_per_thousand: 75)
expect(user.reload.custom_fee_per_thousand).to eq 75
post :set_custom_fee, params: { id: user.id, custom_fee_percent: "5" }
expect(response).to be_successful
expect(user.reload.custom_fee_per_thousand).to eq 50
end
end
describe "POST #toggle_adult_products" do
let(:user) { create(:user) }
context "when all_adult_products is false" do
before do
user.update!(all_adult_products: false)
end
it "toggles all_adult_products to true" do
post :toggle_adult_products, params: { id: user.id }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(user.reload.all_adult_products).to be(true)
end
end
context "when all_adult_products is true" do
before do
user.update!(all_adult_products: true)
end
it "toggles all_adult_products to false" do
post :toggle_adult_products, params: { id: user.id }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(user.reload.all_adult_products).to be(false)
end
end
context "when all_adult_products is nil" do
before do
user.update!(all_adult_products: nil)
end
it "toggles all_adult_products to true" do
post :toggle_adult_products, params: { id: user.id }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(user.reload.all_adult_products).to be(true)
end
end
context "when user is found by email" do
it "toggles all_adult_products successfully" do
user.update!(all_adult_products: false)
post :toggle_adult_products, params: { id: user.email }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(user.reload.all_adult_products).to be(true)
end
end
context "when user is found by username" do
it "toggles all_adult_products successfully" do
user.update!(all_adult_products: false, username: "testuser")
post :toggle_adult_products, params: { id: user.username }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
expect(user.reload.all_adult_products).to be(true)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/action_call_dashboard_controller_spec.rb | spec/controllers/admin/action_call_dashboard_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "inertia_rails/rspec"
require "shared_examples/admin_base_controller_concern"
describe Admin::ActionCallDashboardController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET #index" do
it "renders the inertia page with admin_action_call_infos ordered by call_count descending" do
admin_action_call_info1 = create(:admin_action_call_info, call_count: 3)
admin_action_call_info2 = create(:admin_action_call_info, action_name: "stats", call_count: 5)
get :index
expect(response).to have_http_status(:ok)
expect_inertia.to render_component "Admin/ActionCallDashboard/Index"
expect(inertia.props[:admin_action_call_infos]).to eq([admin_action_call_info2, admin_action_call_info1].map do |info|
{
id: info.id,
controller_name: info.controller_name,
action_name: info.action_name,
call_count: info.call_count
}
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/admin/helper_actions_controller_spec.rb | spec/controllers/admin/helper_actions_controller_spec.rb | # frozen_string_literal: true
RSpec.describe Admin::HelperActionsController do
let(:admin) { create(:admin_user) }
let(:user) { create(:user) }
describe "GET impersonate" do
it "redirects to admin impersonation when authenticated as admin" do
sign_in(admin)
get :impersonate, params: { user_id: user.external_id }
expect(response).to redirect_to(admin_impersonate_path(user_identifier: user.external_id))
end
it "redirects to root path when not authenticated as admin" do
sign_in(create(:user))
get :impersonate, params: { user_id: user.external_id }
expect(response).to redirect_to(root_path)
end
it "returns not found for invalid user" do
sign_in(admin)
get :impersonate, params: { user_id: "invalid" }
expect(response).to have_http_status(:not_found)
end
end
describe "GET stripe_dashboard" do
let(:merchant_account) { create(:merchant_account, charge_processor_id: StripeChargeProcessor.charge_processor_id) }
let(:user_with_stripe) { merchant_account.user }
it "redirects to Stripe dashboard when authenticated as admin" do
sign_in(admin)
get :stripe_dashboard, params: { user_id: user_with_stripe.external_id }
expect(response).to redirect_to("https://dashboard.stripe.com/connect/accounts/#{merchant_account.charge_processor_merchant_id}")
end
it "redirects to root path when not authenticated as admin" do
sign_in(create(:user))
get :stripe_dashboard, params: { user_id: user_with_stripe.external_id }
expect(response).to redirect_to(root_path)
end
it "returns not found when user has no Stripe account" do
sign_in(admin)
get :stripe_dashboard, params: { user_id: user.external_id }
expect(response).to have_http_status(:not_found)
end
it "returns not found for invalid user" do
sign_in(admin)
get :stripe_dashboard, params: { user_id: "invalid" }
expect(response).to have_http_status(:not_found)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/block_email_domains_controller_spec.rb | spec/controllers/admin/block_email_domains_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::BlockEmailDomainsController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET show" do
it "renders the page to suspend users" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq "Admin/BlockEmailDomains/Show"
end
end
describe "PUT update" do
let(:email_domains_to_block) { %w[example.com example.org] }
context "when the specified users IDs are separated by newlines" do
let(:identifiers) { email_domains_to_block.join("\n") }
it "enqueues a job to suspend the specified users" do
put :update, params: { email_domains: { identifiers: } }
expect(BlockObjectWorker.jobs.size).to eq(2)
expect(response).to redirect_to(admin_block_email_domains_url)
expect(flash[:notice]).to eq "Email domains blocked successfully!"
end
it "does not pass expiry date to BlockObjectWorker" do
array_of_args = email_domains_to_block.map { |email_domain| ["email_domain", email_domain, admin_user.id] }
expect(BlockObjectWorker).to receive(:perform_bulk).with(array_of_args, batch_size: 1_000).and_call_original
put :update, params: { email_domains: { identifiers: } }
end
end
context "when the specified users IDs are separated by commas" do
let(:identifiers) { email_domains_to_block.join(", ") }
it "enqueues a job to suspend the specified users" do
put :update, params: { email_domains: { identifiers: } }
expect(BlockObjectWorker.jobs.size).to eq(2)
expect(response).to redirect_to(admin_block_email_domains_url)
expect(flash[:notice]).to eq "Email domains blocked successfully!"
end
it "does not pass expiry date to BlockObjectWorker" do
array_of_args = email_domains_to_block.map { |email_domain| ["email_domain", email_domain, admin_user.id] }
expect(BlockObjectWorker).to receive(:perform_bulk).with(array_of_args, batch_size: 1_000).and_call_original
put :update, params: { email_domains: { identifiers: } }
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/admin/payouts_controller_spec.rb | spec/controllers/admin/payouts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::PayoutsController, type: :controller, inertia: true do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:payment) { create(:payment_completed) }
describe "GET show" do
it "shows a payout" do
sign_in admin_user
get :show, params: { id: payment.id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Payouts/Show")
end
end
describe "POST retry" do
it "retries a failed payout" do
failed_payment = create(:payment_failed)
sign_in admin_user
post :retry, params: { id: failed_payment.id }
expect(response).to be_successful
end
end
describe "POST cancel" do
it "cancels an unclaimed paypal payout" do
unclaimed_payment = create(:payment_unclaimed, processor: PayoutProcessorType::PAYPAL)
sign_in admin_user
post :cancel, params: { id: unclaimed_payment.id }
expect(response).to be_successful
end
end
describe "POST fail" do
it "marks a processing payout as failed" do
processing_payment = create(:payment, created_at: 3.days.ago)
sign_in admin_user
post :fail, params: { id: processing_payment.id }
expect(response).to be_successful
end
end
describe "POST sync" do
it "syncs a paypal payout" do
paypal_payment = create(:payment, processor: PayoutProcessorType::PAYPAL)
sign_in admin_user
post :sync, params: { id: paypal_payment.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/admin/paydays_controller_spec.rb | spec/controllers/admin/paydays_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::PaydaysController do
it_behaves_like "inherits from Admin::BaseController"
let(:next_scheduled_payout_end_date) { User::PayoutSchedule.next_scheduled_payout_end_date }
before do
user = create(:admin_user)
sign_in(user)
end
describe "POST 'pay_user'" do
before do
@user = create(:singaporean_user_with_compliance_info, user_risk_state: "compliant", payment_address: "bob@example.com")
create(:balance, user: @user, amount_cents: 1000, date: next_scheduled_payout_end_date - 3)
create(:balance, user: @user, amount_cents: 500, date: next_scheduled_payout_end_date)
create(:balance, user: @user, amount_cents: 2000, date: next_scheduled_payout_end_date + 1)
end
it "pays the seller for balances up to and including the date passed in params" do
WebMock.stub_request(:post, PAYPAL_ENDPOINT).to_return(body: "CORRELATIONID=c51c5e0cecbce&ACK=Success")
post :pay_user, params: { id: @user.id, payday: { payout_processor: PayoutProcessorType::PAYPAL, payout_period_end_date: next_scheduled_payout_end_date } }
expect(response).to be_redirect
expect(flash[:notice]).to eq("Payment was sent.")
last_payment = Payment.last
expect(last_payment.user_id).to eq(@user.id)
expect(last_payment.amount_cents).to eq(1470)
expect(last_payment.state).to eq("processing")
expect(@user.unpaid_balance_cents).to eq(2000)
end
it "does not pay the user if there are pending payments" do
create(:payment, user: @user)
post :pay_user, params: { id: @user.id, payday: { payout_processor: PayoutProcessorType::PAYPAL, payout_period_end_date: next_scheduled_payout_end_date } }
expect(response).to be_redirect
expect(flash[:notice]).to eq("Payment was not sent.")
expect(@user.payments.count).to eq(1)
end
it "attempts to pay the user via Stripe if the `payout_processor` is 'STRIPE'" do
expect(Payouts).to receive(:create_payments_for_balances_up_to_date_for_users).with(next_scheduled_payout_end_date,
PayoutProcessorType::STRIPE, [@user], from_admin: true
).and_return([Payment.last])
post :pay_user, params: { id: @user.id, payday: { payout_processor: PayoutProcessorType::STRIPE, payout_period_end_date: next_scheduled_payout_end_date } }
expect(response).to be_redirect
expect(flash[:notice]).to eq("Payment was not sent.")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/unblock_email_domains_controller_spec.rb | spec/controllers/admin/unblock_email_domains_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::UnblockEmailDomainsController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:non_admin_user) { create(:user) }
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET show" do
it "renders the page to unsuspend users if admin" do
get :show
expect(response).to be_successful
expect(inertia.component).to eq "Admin/UnblockEmailDomains/Show"
end
end
describe "PUT update" do
let(:email_domains_to_unblock) { %w[example.com example.org] }
let(:identifiers) { email_domains_to_unblock.join("\n") }
it "enqueues a job to unsuspend the specified email domains" do
put :update, params: { email_domains: { identifiers: } }
expect(UnblockObjectWorker.jobs.size).to eq(2)
expect(response).to redirect_to(admin_unblock_email_domains_url)
expect(flash[:notice]).to eq "Email domains unblocked successfully!"
end
it "unblocks email domain", :sidekiq_inline do
BlockedObject.block!(BLOCKED_OBJECT_TYPES[:email_domain], "example.com", nil)
put :update, params: { email_domains: { identifiers: } }
expect(BlockedObject.last.object_value).to eq("example.com")
expect(BlockedObject.last.blocked_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/admin/comments_controller_spec.rb | spec/controllers/admin/comments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::CommentsController do
it_behaves_like "inherits from Admin::BaseController"
describe "POST create" do
let(:user) { create(:user) }
let(:comment_attrs) do
{ content: "comment content", comment_type: "comment", commentable_type: "User", commentable_id: user.id }
end
describe "with a signed in admin user" do
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
it "creates the comment with valid params" do
expect do
post :create, params: { comment: comment_attrs }
end.to change { Comment.count }.by(1)
expect(Comment.last.content).to eq(comment_attrs[:content])
end
it "does not create comment with invalid params" do
expect do
comment_attrs.delete(:content)
post :create, params: { comment: comment_attrs }
end.to raise_error(ActiveRecord::RecordInvalid)
end
end
describe "from an external source" do
it "creates a comment with a valid token" do
expect do
post :create, params: { auth_token: GlobalConfig.get("IFFY_TOKEN"), comment: comment_attrs.merge(author_name: "iffy") }
end.to change { Comment.count }.by(1)
expect(Comment.last.content).to eq(comment_attrs[:content])
end
it "does not create a comment with an invalid token" do
expect do
post :create, params: { comment: comment_attrs }
end.to_not change { Comment.count }
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/admin/sales_reports_controller_spec.rb | spec/controllers/admin/sales_reports_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::SalesReportsController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before(:each) do
sign_in admin_user
end
describe "GET index" do
let(:job_history) { '{"job_id":"123","country_code":"US","start_date":"2023-01-01","end_date":"2023-03-31","enqueued_at":"2023-01-01T00:00:00Z","status":"processing"}' }
before do
allow($redis).to receive(:lrange).with(RedisKey.sales_report_jobs, 0, 19).and_return([job_history])
end
it "renders the page" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq "Admin/SalesReports/Index"
props = inertia.props
expect(props[:title]).to eq("Sales reports")
expect(props[:countries]).to eq Compliance::Countries.for_select.map { |alpha2, name| [name, alpha2] }
expect(props[:sales_types]).to eq GenerateSalesReportJob::SALES_TYPES.map { [_1, _1.humanize] }
expect(props[:job_history]).to eq([JSON.parse(job_history).symbolize_keys])
expect(props[:authenticity_token]).to be_present
end
end
describe "POST create" do
let(:country_code) { "GB" }
let(:start_date) { "2023-01-01" }
let(:end_date) { "2023-03-31" }
let(:sales_type) { GenerateSalesReportJob::ALL_SALES }
let(:params) do
{
sales_report: {
country_code: country_code,
start_date: start_date,
end_date: end_date,
sales_type:,
}
}
end
before do
allow($redis).to receive(:lpush)
allow($redis).to receive(:ltrim)
end
it "enqueues a GenerateSalesReportJob with string dates" do
post :create, params: params
expect(GenerateSalesReportJob).to have_enqueued_sidekiq_job(
country_code,
start_date,
end_date,
GenerateSalesReportJob::ALL_SALES,
true,
nil
)
end
it "stores job details in Redis" do
expect($redis).to receive(:lpush).with(RedisKey.sales_report_jobs, anything)
expect($redis).to receive(:ltrim).with(RedisKey.sales_report_jobs, 0, 19)
post :create, params: params
end
it "303 redirects to the sales reports page with a success message" do
post :create, params: params
expect(response).to redirect_to(admin_sales_reports_path)
expect(response).to have_http_status(:see_other)
expect(flash[:notice]).to eq "Sales report job enqueued successfully!"
end
it "converts dates to strings before passing to job" do
allow(GenerateSalesReportJob).to receive(:perform_async).and_return("job_id_123")
post :create, params: params
expect(GenerateSalesReportJob).to have_received(:perform_async).with(
country_code,
start_date,
end_date,
GenerateSalesReportJob::ALL_SALES,
true,
nil
)
end
context "when the form is invalid" do
let(:params) do
{
sales_report: {
country_code: "",
start_date: "",
end_date: ""
}
}
end
it "302 redirects to the sales reports page with an error message" do
post :create, params: params
expect(response).to redirect_to(admin_sales_reports_path)
expect(response).to have_http_status(:found)
expect(flash[:alert]).to eq "Invalid form submission. Please fix the errors."
expect(session[:inertia_errors]).to eq({
sales_report: {
country_code: ["Please select a country"],
start_date: ["Invalid date format. Please use YYYY-MM-DD format"],
end_date: ["Invalid date format. Please use YYYY-MM-DD format"],
sales_type: ["Invalid sales type, should be all_sales or discover_sales."]
}
})
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/admin/guids_controller_spec.rb | spec/controllers/admin/guids_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::GuidsController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:user1) { create(:user) }
let(:user2) { create(:user) }
let(:user3) { create(:user) }
let(:browser_guid) { SecureRandom.uuid }
let(:admin_user) { create(:admin_user) }
before do
create(:event, user_id: user1.id, browser_guid: browser_guid)
create(:event, user_id: user2.id, browser_guid: browser_guid)
create(:event, user_id: user3.id, browser_guid: browser_guid)
sign_in admin_user
end
describe "GET show" do
it "returns successful response with Inertia page data" do
get :show, params: { id: browser_guid }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Compliance/Guids/Show")
end
it "returns unique users for the supplied browser GUID" do
get :show, params: { id: browser_guid }
expect(response).to be_successful
expect(assigns(:users).to_a).to match_array [user1, user2, user3]
end
it "returns JSON response when requested" do
get :show, params: { id: browser_guid }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([user1.external_id, user2.external_id, user3.external_id])
expect(response.parsed_body["pagination"]).to be_present
end
it "returns an empty array when no users are found for the GUID" do
non_existent_guid = SecureRandom.uuid
get :show, params: { id: non_existent_guid }
expect(response).to be_successful
expect(assigns(:users).to_a).to be_empty
end
it "returns only users with events for the specific GUID" do
other_user = create(:user)
other_guid = SecureRandom.uuid
create(:event, user_id: other_user.id, browser_guid: other_guid)
get :show, params: { id: browser_guid }
expect(response).to be_successful
expect(assigns(:users).to_a).to match_array [user1, user2, user3]
expect(assigns(:users).to_a).not_to include(other_user)
end
it "paginates results" do
get :show, params: { id: browser_guid, page: 1 }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([user1.external_id, user2.external_id, user3.external_id])
expect(response.parsed_body["pagination"]).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/admin/purchases_controller_spec.rb | spec/controllers/admin/purchases_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::PurchasesController, :vcr, inertia: true do
it_behaves_like "inherits from Admin::BaseController"
before do
@admin_user = create(:admin_user)
sign_in @admin_user
end
describe "#show" do
before do
@purchase = create(:purchase)
end
it "redirects numeric ID to external_id" do
get :show, params: { external_id: @purchase.id }
expect(response).to redirect_to(admin_purchase_path(@purchase.external_id))
end
it "returns successful response with Inertia page data" do
expect(Admin::PurchasePresenter).to receive(:new).with(@purchase).and_call_original
get :show, params: { external_id: @purchase.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Purchases/Show")
end
it "raises ActionController::RoutingError when purchase is not found" do
expect { get :show, params: { external_id: "invalid-id" } }.to raise_error(ActionController::RoutingError)
end
it "finds the purchase correctly when loaded via external id" do
expect(Purchase).not_to receive(:find_by_stripe_transaction_id)
expect(Purchase).to receive(:find_by_external_id).and_call_original
get :show, params: { external_id: @purchase.external_id }
expect(assigns(:purchase)).to eq(@purchase)
assert_response :success
end
it "finds the purchase correctly when loaded via numeric external id" do
expect(Purchase).to receive(:find_by_external_id_numeric).and_call_original
get :show, params: { external_id: @purchase.external_id_numeric }
expect(assigns(:purchase)).to eq(@purchase)
assert_response :success
end
it "finds the purchase correctly when loaded via stripe_transaction_id" do
expect(Purchase).to receive(:find_by_stripe_transaction_id).and_call_original
get :show, params: { external_id: @purchase.stripe_transaction_id }
expect(assigns(:purchase)).to eq(@purchase)
assert_response :success
end
end
describe "POST refund_for_fraud" do
before do
@purchase = create(:purchase_in_progress, chargeable: create(:chargeable), purchaser: create(:user))
@purchase.process!
@purchase.mark_successful!
end
it "refunds the purchase and blocks the buyer" do
comment_content = "Buyer blocked by Admin (#{@admin_user.email})"
expect do
post :refund_for_fraud, params: { external_id: @purchase.external_id }
expect(@purchase.reload.stripe_refunded).to be(true)
expect(@purchase.buyer_blocked?).to eq(true)
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end.to change { @purchase.comments.where(content: comment_content, comment_type: "note", author_id: @admin_user.id).count }.by(1)
.and change { @purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: @admin_user.id, purchase: @purchase).count }.by(1)
end
end
describe "POST refund_taxes_only" do
before do
@purchase = create(:purchase_in_progress, chargeable: create(:chargeable), purchaser: create(:user))
@purchase.process!
@purchase.mark_successful!
end
it "successfully refunds taxes when refundable taxes are available" do
allow_any_instance_of(Purchase).to receive(:refund_gumroad_taxes!).with(refunding_user_id: @admin_user.id, note: nil, business_vat_id: nil).and_return(true)
post :refund_taxes_only, params: { external_id: @purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end
it "includes note and business_vat_id when provided" do
allow_any_instance_of(Purchase).to receive(:refund_gumroad_taxes!).with(refunding_user_id: @admin_user.id, note: "Tax exemption request", business_vat_id: "VAT123456").and_return(true)
post :refund_taxes_only, params: {
external_id: @purchase.external_id,
note: "Tax exemption request",
business_vat_id: "VAT123456"
}
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end
it "returns error when tax refund fails" do
allow_any_instance_of(Purchase).to receive(:refund_gumroad_taxes!).with(refunding_user_id: @admin_user.id, note: nil, business_vat_id: nil).and_return(false)
allow_any_instance_of(Purchase).to receive(:errors).and_return(
double(full_messages: double(to_sentence: "Tax already refunded and Invalid tax amount"))
)
post :refund_taxes_only, params: { external_id: @purchase.external_id }
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(false)
expect(response.parsed_body["message"]).to eq("Tax already refunded and Invalid tax amount")
end
it "raises error when purchase is not found" do
expect { post :refund_taxes_only, params: { external_id: "invalid-id" } }.to raise_error(ActionController::RoutingError)
end
end
describe "POST undelete" do
before do
@purchase = create(:purchase, purchaser: create(:user), is_deleted_by_buyer: true)
end
it "undeletes the purchase and creates comments" do
comment_content = "Purchase undeleted by Admin (#{@admin_user.email})"
expect do
post :undelete, params: { external_id: @purchase.external_id }
expect(@purchase.reload.is_deleted_by_buyer).to be(false)
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end.to change { @purchase.comments.where(content: comment_content, comment_type: "note", author_id: @admin_user.id).count }.by(1)
.and change { @purchase.purchaser.comments.where(content: comment_content, comment_type: "note", author_id: @admin_user.id, purchase: @purchase).count }.by(1)
end
it "handles purchase that is already undeleted" do
@purchase.update!(is_deleted_by_buyer: false)
expect do
post :undelete, params: { external_id: @purchase.external_id }
expect(@purchase.reload.is_deleted_by_buyer).to be(false)
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end.not_to change { @purchase.comments.count }
end
it "handles purchase without purchaser" do
@purchase.update!(purchaser: nil)
comment_content = "Purchase undeleted by Admin (#{@admin_user.email})"
expect do
post :undelete, params: { external_id: @purchase.external_id }
expect(@purchase.reload.is_deleted_by_buyer).to be(false)
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
end.to change { @purchase.comments.where(content: comment_content, comment_type: "note", author_id: @admin_user.id).count }.by(1)
end
it "raises error when purchase is not found" do
expect { post :undelete, params: { external_id: "invalid-id" } }.to raise_error(ActionController::RoutingError)
end
end
describe "POST resend_receipt" do
let(:buyer) { create(:user) }
let(:new_email) { "new@example.com" }
context "when updating email for subscription purchases" do
it "updates original_purchase email for subscription purchases" do
subscription = create(:subscription, user: buyer)
create(:purchase, email: "old@example.com", purchaser: buyer, is_original_subscription_purchase: true, subscription: subscription)
recurring_purchase = create(:purchase, email: "old@example.com", purchaser: buyer, subscription: subscription)
post :resend_receipt, params: {
external_id: recurring_purchase.external_id,
resend_receipt: { email_address: new_email }
}
expect(response).to be_successful
expect(response.parsed_body["success"]).to be(true)
recurring_purchase.reload
expect(recurring_purchase.email).to eq(new_email)
subscription.reload
expect(subscription.original_purchase.email).to eq(new_email)
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/admin/links_controller_spec.rb | spec/controllers/admin/links_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::LinksController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:product) { create(:product) }
before do
sign_in admin_user
@request.env["HTTP_REFERER"] = "where_i_came_from"
end
describe "GET legacy_purchases" do
def create_purchases_in_order(count, product, options = {})
count.times.map do |n|
create(:purchase, options.merge(link: product, created_at: Time.current + n.minutes))
end
end
def purchase_admin_review_json(purchases)
purchases.map { |purchase| purchase.as_json(admin_review: true) }
end
describe "pagination" do
before do
@purchases = create_purchases_in_order(10, product)
end
it "returns the purchases of the specified page" do
get :legacy_purchases, params: { external_id: product.external_id, is_affiliate_user: "false", page: 2, per_page: 2, format: :json }
expect(response).to be_successful
expect(response.parsed_body["purchases"]).to eq purchase_admin_review_json(@purchases.reverse[2..3])
expect(response.parsed_body["page"]).to eq 2
end
end
context "when user purchases are requested" do
before do
@purchases = create_purchases_in_order(2, product)
end
it "returns user purchases" do
get :legacy_purchases, params: { external_id: product.external_id, is_affiliate_user: "false", format: :json }
expect(response).to be_successful
expect(response.parsed_body["purchases"]).to eq purchase_admin_review_json(@purchases.reverse)
end
end
context "when affiliate purchases are requested" do
before do
affiliate = create(:direct_affiliate)
@affiliate_user = affiliate.affiliate_user
@purchases = create_purchases_in_order(2, product, affiliate_id: affiliate.id)
end
it "returns affiliate purchases" do
get :legacy_purchases, params: { external_id: product.external_id, is_affiliate_user: "true", user_id: @affiliate_user.id, format: :json }
expect(response).to be_successful
expect(response.parsed_body["purchases"]).to eq purchase_admin_review_json(@purchases.reverse)
end
end
end
describe "GET show" do
it "redirects numeric ID to external_id" do
get :show, params: { external_id: product.id }
expect(response).to redirect_to(admin_product_path(product.external_id))
end
it "renders the product page if looked up via external_id" do
get :show, params: { external_id: product.external_id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Products/Show")
expect(inertia.props[:title]).to eq(product.name)
expect(inertia.props[:product]).to eq(Admin::ProductPresenter::Card.new(product:, pundit_user: SellerContext.new(user: admin_user, seller: product.user)).props)
expect(inertia.props[:user]).to eq(Admin::UserPresenter::Card.new(user: product.user, pundit_user: SellerContext.new(user: admin_user, seller: product.user)).props)
end
describe "multiple matches by permalink" do
context "when multiple products matched by permalink" do
it "lists all matches" do
product_1 = create(:product, unique_permalink: "a", custom_permalink: "match")
product_2 = create(:product, unique_permalink: "b", custom_permalink: "match")
create(:product, unique_permalink: "c", custom_permalink: "should-not-match")
get :show, params: { external_id: product_1.custom_permalink }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Products/MultipleMatches")
expect(inertia.props[:product_matches]).to contain_exactly(hash_including(external_id: product_1.external_id), hash_including(external_id: product_2.external_id))
end
end
context "when only one product matched by permalink" do
it "renders the product page" do
product = create(:product, unique_permalink: "a", custom_permalink: "match")
get :show, params: { external_id: product.custom_permalink }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Products/Show")
expect(inertia.props[:title]).to eq(product.name)
expect(inertia.props[:product]).to eq(Admin::ProductPresenter::Card.new(product:, pundit_user: SellerContext.new(user: admin_user, seller: product.user)).props)
expect(inertia.props[:user]).to eq(Admin::UserPresenter::Card.new(user: product.user, pundit_user: SellerContext.new(user: admin_user, seller: product.user)).props)
end
end
context "when no products matched by permalink" do
it "raises a 404" do
expect do
get :show, params: { external_id: "match" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
end
end
describe "DELETE destroy" do
it "deletes the product" do
delete :destroy, params: { external_id: product.external_id }
expect(response).to be_successful
expect(product.reload.deleted_at).to be_present
end
it "raises a 404 if the product is not found" do
expect do
delete :destroy, params: { external_id: "invalid-id" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
describe "POST restore" do
let(:product) { create(:product, deleted_at: 1.day.ago) }
it "restores the product" do
post :restore, params: { external_id: product.external_id }
expect(response).to be_successful
expect(product.reload.deleted_at).to be_nil
end
it "raises a 404 if the product is not found" do
expect do
post :restore, params: { external_id: "invalid-id" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
describe "POST publish" do
let(:product) { create(:product, purchase_disabled_at: Time.current) }
it "publishes the product" do
post :publish, params: { external_id: product.external_id }
expect(response).to be_successful
expect(product.reload.purchase_disabled_at).to be_nil
end
it "raises a 404 if the product is not found" do
expect do
post :publish, params: { external_id: "invalid-id" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
describe "DELETE unpublish" do
let(:product) { create(:product, purchase_disabled_at: nil) }
it "unpublishes the product" do
delete :unpublish, params: { external_id: product.external_id }
expect(response).to be_successful
expect(product.reload.purchase_disabled_at).to be_present
end
it "raises a 404 if the product is not found" do
expect do
delete :unpublish, params: { external_id: "invalid-id" }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
describe "POST is_adult" do
it "marks the product as adult" do
post :is_adult, params: { external_id: product.external_id, is_adult: true }
expect(response).to be_successful
expect(product.reload.is_adult).to be(true)
post :is_adult, params: { external_id: product.external_id, is_adult: false }
expect(response).to be_successful
expect(product.reload.is_adult).to be(false)
end
it "raises a 404 if the product is not found" do
expect do
post :is_adult, params: { external_id: "invalid-id", is_adult: true }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/affiliates_controller_spec.rb | spec/controllers/admin/affiliates_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::AffiliatesController, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
before do
@admin_user = create(:admin_user)
sign_in @admin_user
end
describe "GET 'index'" do
context "when there's one matching affiliate in search result" do
before do
@affiliate_user = create(:direct_affiliate).affiliate_user
end
it "redirects to affiliate's admin page" do
get :index, params: { query: @affiliate_user.email }
expect(response).to redirect_to admin_affiliate_path(@affiliate_user)
end
end
context "when there are multiple affiliates in search result" do
before do
@affiliate_users = 10.times.map do
user = create(:user, name: "test")
create(:direct_affiliate, affiliate_user: user)
user
end
end
it "renders search results" do
get :index, params: { query: "test" }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Affiliates/Index")
expect(assigns[:users].to_a).to match_array(@affiliate_users)
end
it "returns JSON response when requested" do
get :index, params: { query: "test" }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"].map { _1["id"] }).to match_array(@affiliate_users.drop(5).map(&:external_id))
expect(response.parsed_body["pagination"]).to be_present
end
end
end
describe "GET 'show'" do
let(:affiliate_user) { create(:user, name: "Sam") }
context "when affiliate account is present" do
before do
create(:direct_affiliate, affiliate_user:)
end
it "returns page successfully" do
get :show, params: { id: affiliate_user.id }
expect(response).to be_successful
expect(response.body).to have_text(affiliate_user.name)
expect(assigns[:title]).to eq "Sam affiliate on Gumroad"
end
end
context "when affiliate account is not present" do
it "raises ActionController::RoutingError" do
expect do
get :show, params: { id: affiliate_user.id }
end.to raise_error(ActionController::RoutingError, "Not Found")
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/unreviewed_users_controller_spec.rb | spec/controllers/admin/unreviewed_users_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::UnreviewedUsersController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin) { create(:admin_user) }
before do
sign_in admin
end
describe "GET #index" do
context "when not logged in" do
before { sign_out admin }
it "redirects to login" do
get :index
expect(response).to redirect_to(login_path(next: admin_unreviewed_users_path))
end
end
context "when logged in as non-admin" do
let(:regular_user) { create(:user) }
before do
sign_out admin
sign_in regular_user
end
it "redirects to root" do
get :index
expect(response).to redirect_to(root_path)
end
end
context "when logged in as admin" do
before do
$redis.del(RedisKey.unreviewed_users_cutoff_date)
end
context "when no cached data exists" do
before do
$redis.del(RedisKey.unreviewed_users_data)
end
it "returns empty state with default cutoff_date" do
get :index
expect(response).to be_successful
expect(inertia.component).to eq "Admin/UnreviewedUsers/Index"
expect(inertia.props[:users]).to be_empty
expect(inertia.props[:total_count]).to eq(0)
expect(inertia.props[:cutoff_date]).to eq("2024-01-01")
end
end
context "when cached data exists" do
let!(:unreviewed_user) do
create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago)
end
before do
create(:balance, user: unreviewed_user, amount_cents: 5000)
Admin::UnreviewedUsersService.cache_users_data!
end
it "returns cached users with props from service" do
get :index
expect(response).to be_successful
expect(inertia.props[:users].size).to eq(1)
expect(inertia.props[:users].first[:id]).to eq(unreviewed_user.id)
expect(inertia.props[:total_count]).to eq(1)
expect(inertia.props[:cutoff_date]).to eq("2024-01-01")
end
end
context "when user is reviewed after caching" do
let!(:user) do
create(:user, user_risk_state: "not_reviewed", created_at: 1.year.ago)
end
before do
create(:balance, user:, amount_cents: 5000)
Admin::UnreviewedUsersService.cache_users_data!
user.update!(user_risk_state: "compliant")
end
it "filters out users who are no longer not_reviewed" do
get :index
expect(inertia.props[:users]).to be_empty
# total_count still reflects cached total
expect(inertia.props[:total_count]).to eq(1)
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/admin/purchases/comments_controller_spec.rb | spec/controllers/admin/purchases/comments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "shared_examples/admin_commentable_concern"
describe Admin::Purchases::CommentsController do
it_behaves_like "inherits from Admin::BaseController"
let(:purchase) { create(:purchase) }
it_behaves_like "Admin::Commentable" do
let(:commentable_object) { purchase }
let(:route_params) { { purchase_external_id: purchase.external_id } }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/affiliates/products_controller_spec.rb | spec/controllers/admin/affiliates/products_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::Affiliates::ProductsController, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:affiliate_user) { create(:user) }
let!(:published_product) { create(:product, name: "Published product") }
let!(:unpublished_product) { create(:product, name: "Unpublished product", purchase_disabled_at: Time.current) }
let!(:deleted_product) { create(:product, name: "Deleted product", deleted_at: Time.current) }
let!(:banned_product) { create(:product, name: "Banned product", banned_at: Time.current) }
let!(:alive_affiliate) { create(:direct_affiliate, affiliate_user:, products: [published_product, unpublished_product, deleted_product, banned_product]) }
let!(:product_by_deleted_affiliate) { create(:product, name: "Product by deleted affiliate") }
let!(:deleted_affiliate) { create(:direct_affiliate, affiliate_user:, products: [product_by_deleted_affiliate], deleted_at: Time.current) }
before do
sign_in admin_user
end
describe "GET index" do
before do
get :index, params: { affiliate_id: affiliate_user.id }
end
it "returns successful response with Inertia page data" do
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Affiliates/Products/Index")
expect(inertia.props[:products].map { _1[:external_id] }).to contain_exactly(published_product.external_id, unpublished_product.external_id)
expect(inertia.props[:pagination]).to eq({ pages: 1, page: 1 })
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/affiliates/products/purchases_controller_spec.rb | spec/controllers/admin/affiliates/products/purchases_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Affiliates::Products::PurchasesController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET index" do
let(:product) { create(:product) }
let(:affiliate_user) { create(:user) }
let(:affiliate) { create(:direct_affiliate, affiliate_user: affiliate_user, seller: product.user) }
let!(:affiliate_purchase) { create(:purchase, link: product, affiliate: affiliate) }
it "returns purchases and pagination for the affiliate" do
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(1)
expect(purchases.first["external_id"]).to eq(affiliate_purchase.external_id)
expect(response.parsed_body["pagination"]).to be_present
end
it "returns only purchases for the affiliate user" do
non_affiliate_purchase = create(:purchase, link: product, affiliate: nil)
other_affiliate = create(:direct_affiliate, affiliate_user: create(:user), seller: product.user)
other_affiliate_purchase = create(:purchase, link: product, affiliate: other_affiliate)
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
purchase_external_ids = purchases.map { |p| p["external_id"] }
expect(purchase_external_ids).to include(affiliate_purchase.external_id)
expect(purchase_external_ids).not_to include(non_affiliate_purchase.external_id)
expect(purchase_external_ids).not_to include(other_affiliate_purchase.external_id)
end
it "does not return affiliate purchases from other products" do
other_product = create(:product)
other_affiliate = create(:direct_affiliate, affiliate_user: affiliate_user, seller: other_product.user)
other_product_purchase = create(:purchase, link: other_product, affiliate: other_affiliate)
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
purchase_external_ids = purchases.map { |p| p["external_id"] }
expect(purchase_external_ids).to include(affiliate_purchase.external_id)
expect(purchase_external_ids).not_to include(other_product_purchase.external_id)
end
context "with pagination parameters" do
before do
create_list(:purchase, 7, link: product, affiliate: affiliate)
end
it "accepts per_page and page parameters" do
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id, per_page: 5, page: 1 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(5)
pagination = response.parsed_body["pagination"]
expect(pagination).to be_present
end
it "returns the correct page of results" do
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id, per_page: 5, page: 2 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(3) # 8 total - 5 on page 1 = 3 on page 2
end
it "respects per_page limit" do
get :index, params: { product_external_id: product.external_id, affiliate_id: affiliate_user.id, per_page: 3, page: 1 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases.length).to eq(3)
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/admin/compliance/cards_controller_spec.rb | spec/controllers/admin/compliance/cards_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Compliance::CardsController do
it_behaves_like "inherits from Admin::BaseController"
before do
@admin_user = create(:admin_user)
sign_in @admin_user
end
describe "POST refund" do
context "when stripe_fingerprint is blank" do
it "returns an error" do
post :refund
expect(response.parsed_body["success"]).to eq(false)
end
end
context "when stripe_fingerprint is not blank" do
let(:stripe_fingerprint) { "FakeFingerprint" }
let!(:successful_purchase) { create(:purchase, stripe_fingerprint:, purchase_state: "successful") }
let!(:failed_purchase) { create(:purchase, stripe_fingerprint:, purchase_state: "failed") }
let!(:disputed_purchase) { create(:purchase, stripe_fingerprint:, chargeback_date: Time.current) }
let!(:refunded_purchase) { create(:refunded_purchase, stripe_fingerprint:) }
it "enqueues jobs" do
post :refund, params: { stripe_fingerprint: }
expect(RefundPurchaseWorker).to have_enqueued_sidekiq_job(successful_purchase.id, @admin_user.id, Refund::FRAUD)
expect(RefundPurchaseWorker).to_not have_enqueued_sidekiq_job(failed_purchase.id, @admin_user.id, Refund::FRAUD)
expect(RefundPurchaseWorker).to_not have_enqueued_sidekiq_job(disputed_purchase.id, @admin_user.id, Refund::FRAUD)
expect(RefundPurchaseWorker).to_not have_enqueued_sidekiq_job(refunded_purchase.id, @admin_user.id, Refund::FRAUD)
expect(response.parsed_body["success"]).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/admin/products/details_controller_spec.rb | spec/controllers/admin/products/details_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Products::DetailsController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET show" do
let(:product) { create(:product) }
it "returns product details" do
get :show, params: { product_external_id: product.external_id }, format: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["details"]).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/admin/products/staff_picked_controller_spec.rb | spec/controllers/admin/products/staff_picked_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "shared_examples/authorize_called"
describe Admin::Products::StaffPickedController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
let(:product) { create(:product, :recommendable) }
describe "POST create" do
it_behaves_like "authorize called for action", :post, :create do
let(:policy_klass) { Admin::Products::StaffPicked::LinkPolicy }
let(:record) { product }
let(:request_params) { { product_external_id: product.external_id } }
end
context "when product doesn't have an associated staff_picked_product" do
it "creates a record" do
expect do
post :create, params: { product_external_id: product.external_id }, format: :json
end.to change { StaffPickedProduct.all.count }.by(1)
expect(product.reload.staff_picked?).to eq(true)
end
end
context "when product has a deleted staff_picked_product record" do
before do
product.create_staff_picked_product!(deleted_at: Time.current)
end
it "updates the record as not deleted" do
post :create, params: { product_external_id: product.external_id }, format: :json
expect(product.reload.staff_picked?).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/admin/products/comments_controller_spec.rb | spec/controllers/admin/products/comments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "shared_examples/admin_commentable_concern"
describe Admin::Products::CommentsController do
it_behaves_like "inherits from Admin::BaseController"
let(:product) { create(:product) }
it_behaves_like "Admin::Commentable" do
let(:commentable_object) { product }
let(:route_params) { { product_external_id: product.external_id } }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/products/purchases_controller_spec.rb | spec/controllers/admin/products/purchases_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Products::PurchasesController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET index" do
let(:product) { create(:product) }
let!(:purchase) { create(:purchase, link: product) }
it "returns purchases and pagination" do
get :index, params: { product_external_id: product.external_id }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(1)
expect(purchases.first["external_id"]).to eq(purchase.external_id)
expect(response.parsed_body["pagination"]).to be_present
end
it "returns only purchases for the specified product" do
other_product = create(:product)
other_purchase = create(:purchase, link: other_product)
get :index, params: { product_external_id: product.external_id }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
purchase_external_ids = purchases.map { |p| p["external_id"] }
expect(purchase_external_ids).to include(purchase.external_id)
expect(purchase_external_ids).not_to include(other_purchase.external_id)
end
context "with pagination parameters" do
before do
create_list(:purchase, 7, link: product)
end
it "accepts per_page and page parameters" do
get :index, params: { product_external_id: product.external_id, per_page: 5, page: 1 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(5)
pagination = response.parsed_body["pagination"]
expect(pagination).to be_present
end
it "returns the correct page of results" do
get :index, params: { product_external_id: product.external_id, per_page: 5, page: 2 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases).to be_present
expect(purchases.length).to eq(3) # 8 total - 5 on page 1 = 3 on page 2
end
it "respects per_page limit" do
get :index, params: { product_external_id: product.external_id, per_page: 3, page: 1 }, format: :json
expect(response).to have_http_status(:ok)
purchases = response.parsed_body["purchases"]
expect(purchases.length).to eq(3)
end
end
end
describe "POST mass_refund_for_fraud" do
let(:product) { create(:product) }
let!(:successful_purchase) { create(:purchase, link: product) }
let!(:failed_purchase) { create(:failed_purchase, link: product) }
it "enqueues the job with correct parameters" do
expect(MassRefundForFraudJob).to receive(:perform_async).with(
product.id,
[successful_purchase.external_id, failed_purchase.external_id],
admin_user.id
)
post :mass_refund_for_fraud,
params: { product_external_id: product.external_id, purchase_ids: [successful_purchase.external_id, failed_purchase.external_id] },
format: :json
body = response.parsed_body
expect(response).to have_http_status(:ok)
expect(body["success"]).to eq(true)
expect(body["message"]).to include("Processing 2 fraud refunds")
end
it "requires purchase ids" do
post :mass_refund_for_fraud, params: { product_external_id: product.external_id, purchase_ids: [] }, as: :json, format: :json
expect(response).to have_http_status(:unprocessable_entity)
expect(response.parsed_body["success"]).to eq(false)
end
it "rejects purchases that do not belong to the product" do
other_purchase = create(:purchase)
post :mass_refund_for_fraud,
params: { product_external_id: product.external_id, purchase_ids: [other_purchase.external_id] },
format: :json
expect(response).to have_http_status(:unprocessable_entity)
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/admin/products/infos_controller_spec.rb | spec/controllers/admin/products/infos_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Products::InfosController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET show" do
let(:product) { create(:product) }
it "returns product info" do
get :show, params: { product_external_id: product.external_id }, format: :json
expect(response).to have_http_status(:ok)
expect(response.parsed_body["info"]).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/admin/users/latest_posts_controller_spec.rb | spec/controllers/admin/users/latest_posts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::LatestPostsController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
before do
sign_in admin_user
end
describe "GET 'index'" do
context "when user has posts" do
let!(:posts) { create_list(:post, 6, seller: user) }
it "returns the user's last 5 created posts as JSON" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body.length).to eq(5)
end
end
context "when user has no posts" do
it "returns an empty array" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
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/admin/users/stats_controller_spec.rb | spec/controllers/admin/users/stats_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::StatsController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
before do
sign_in admin_user
end
describe "GET 'index'" do
let(:product) { create(:product, user: user, price_cents: 10_000) }
it "returns the user's stats as JSON" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body).to eq(
"total" => "$0",
"balance" => "$0",
"chargeback_volume" => "NA",
"chargeback_count" => "NA"
)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/users/merchant_accounts_controller_spec.rb | spec/controllers/admin/users/merchant_accounts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::MerchantAccountsController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
before do
sign_in admin_user
end
describe "GET 'index'" do
context "when user has no merchant accounts" do
it "returns empty merchant accounts and false for stripe account" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body["merchant_accounts"]).to eq([])
expect(response.parsed_body["has_stripe_account"]).to eq(false)
end
end
context "when user has live merchant accounts" do
let!(:paypal_account) { create(:merchant_account_paypal, user: user) }
let!(:stripe_account) { create(:merchant_account, user: user) }
it "returns merchant accounts with expected fields" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body["merchant_accounts"].length).to eq(2)
merchant_account = response.parsed_body["merchant_accounts"].first
expect(merchant_account.keys).to match_array(%w[charge_processor_id external_id alive charge_processor_alive])
end
it "returns true for has_stripe_account" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body["has_stripe_account"]).to eq(true)
end
end
context "when user has deleted or inactive merchant accounts" do
let!(:deleted_account) do
create(:merchant_account, user: user).tap do |ma|
ma.update!(charge_processor_deleted_at: Time.current)
end
end
let!(:inactive_account) do
create(:merchant_account, user: user).tap do |ma|
ma.mark_deleted!
end
end
it "returns false for has_stripe_account" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body["has_stripe_account"]).to eq(false)
end
end
context "when user has only paypal accounts" do
let!(:paypal_account) { create(:merchant_account_paypal, user: user) }
it "returns false for has_stripe_account" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body["has_stripe_account"]).to eq(false)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/users/payouts_controller_spec.rb | spec/controllers/admin/users/payouts_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::Users::PayoutsController, type: :controller, inertia: true do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:seller) { create(:user) }
let(:payout_period_end_date) { Date.today - 1 }
describe "GET index" do
render_views
let!(:payout_1) { create(:payment_completed, user: seller) }
let!(:payout_2) { create(:payment_failed, user: seller) }
let!(:other_user_payout) { create(:payment_failed) }
it "lists all the payouts for a user" do
sign_in admin_user
get :index, params: { user_id: seller.id }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Users/Payouts/Index")
expect(inertia.props[:payouts]).to contain_exactly(
hash_including(id: payout_1.id),
hash_including(id: payout_2.id)
)
end
end
describe "POST pause" do
before do
sign_in admin_user
end
it "pauses payouts for seller, sets the pause source as admin, and saves the provided reason" do
expect(seller.payouts_paused_internally?).to be false
expect(seller.payouts_paused_by_source).to be nil
expect(seller.payouts_paused_for_reason).to be nil
expect do
post :pause, params: { user_id: seller.id, pause_payouts: { reason: "Chargeback rate too high." } }, format: :json
end.to change { seller.comments.with_type_payouts_paused.count }.by(1)
expect(seller.reload.payouts_paused_internally?).to be true
expect(seller.payouts_paused_by).to eq(admin_user.id)
expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_ADMIN)
expect(seller.payouts_paused_for_reason).to eq("Chargeback rate too high.")
end
it "pauses payouts for seller and sets the pause source as admin even if no reason is provided" do
expect(seller.payouts_paused_internally?).to be false
expect(seller.payouts_paused_by_source).to be nil
expect(seller.payouts_paused_for_reason).to be nil
expect do
post :pause, params: { user_id: seller.id, pause_payouts: { reason: nil } }, format: :json
end.not_to change { seller.comments.with_type_payouts_paused.count }
expect(seller.reload.payouts_paused_internally?).to be true
expect(seller.payouts_paused_by).to eq(admin_user.id)
expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_ADMIN)
expect(seller.payouts_paused_for_reason).to be nil
end
end
describe "POST resume" do
before do
seller.update!(payouts_paused_internally: true)
sign_in admin_user
end
it "resumes payouts for seller and clears the payout pause source if payouts are paused by admin" do
expect(seller.payouts_paused_internally?).to be true
expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_ADMIN)
expect(seller.payouts_paused_for_reason).to be nil
expect do
post :resume, params: { user_id: seller.id }, format: :json
end.to change { seller.comments.with_type_payouts_resumed.count }.by(1)
expect(seller.reload.payouts_paused_internally?).to be false
expect(seller.payouts_paused_by).to be nil
expect(seller.payouts_paused_by_source).to be nil
expect(seller.payouts_paused_for_reason).to be nil
end
it "resumes payouts for seller and clears the payout pause source if payouts are paused by stripe" do
seller.update!(payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_STRIPE)
expect(seller.reload.payouts_paused_internally?).to be true
expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_STRIPE)
expect(seller.payouts_paused_for_reason).to be nil
expect do
post :resume, params: { user_id: seller.id }, format: :json
end.to change { seller.comments.with_type_payouts_resumed.count }.by(1)
expect(seller.reload.payouts_paused_internally?).to be false
expect(seller.payouts_paused_by).to be nil
expect(seller.payouts_paused_by_source).to be nil
expect(seller.payouts_paused_for_reason).to be nil
end
it "resumes payouts for seller and clears the payout pause source if payouts are paused by the system" do
seller.update!(payouts_paused_by: User::PAYOUT_PAUSE_SOURCE_SYSTEM)
expect(seller.reload.payouts_paused_internally?).to be true
expect(seller.payouts_paused_by_source).to eq(User::PAYOUT_PAUSE_SOURCE_SYSTEM)
expect(seller.payouts_paused_for_reason).to be nil
expect do
post :resume, params: { user_id: seller.id }, format: :json
end.to change { seller.comments.with_type_payouts_resumed.count }.by(1)
expect(seller.reload.payouts_paused_internally?).to be false
expect(seller.payouts_paused_by).to be nil
expect(seller.payouts_paused_by_source).to be nil
expect(seller.payouts_paused_for_reason).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/admin/users/comments_controller_spec.rb | spec/controllers/admin/users/comments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "shared_examples/admin_commentable_concern"
describe Admin::Users::CommentsController do
it_behaves_like "inherits from Admin::BaseController"
let(:user) { create(:user) }
it_behaves_like "Admin::Commentable" do
let(:commentable_object) { user }
let(:route_params) { { user_id: user.id } }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/users/guids_controller_spec.rb | spec/controllers/admin/users/guids_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::GuidsController do
it_behaves_like "inherits from Admin::BaseController"
let(:user1) { create(:user) }
let(:user2) { create(:user) }
let(:user3) { create(:user) }
let(:browser_guid1) { SecureRandom.uuid }
let(:browser_guid2) { SecureRandom.uuid }
let(:browser_guid3) { SecureRandom.uuid }
let(:admin_user) { create(:admin_user) }
before do
create(:event, user_id: user1.id, browser_guid: browser_guid1)
create(:event, user_id: user1.id, browser_guid: browser_guid2)
create(:event, user_id: user2.id, browser_guid: browser_guid2)
create(:event, user_id: user1.id, browser_guid: browser_guid3)
create(:event, user_id: user2.id, browser_guid: browser_guid3)
create(:event, user_id: user3.id, browser_guid: browser_guid3)
sign_in admin_user
end
describe "GET index" do
it "returns unique browser GUIDs with unique user IDs for the supplied user ID" do
get :index, params: { user_id: user1.id }
expect(response).to be_successful
expected_value = [
{ "guid" => browser_guid1, "user_ids" => [user1.id] },
{ "guid" => browser_guid2, "user_ids" => [user1.id, user2.id] },
{ "guid" => browser_guid3, "user_ids" => [user1.id, user2.id, user3.id] }
]
expect(response.parsed_body).to match_array(expected_value)
end
it "returns an empty array when no GUIDs are found for the user" do
user_without_events = create(:user)
get :index, params: { user_id: user_without_events.id }
expect(response).to be_successful
expect(response.parsed_body).to be_empty
end
it "returns only GUIDs associated with the specified user" do
other_user = create(:user)
other_guid = SecureRandom.uuid
create(:event, user_id: other_user.id, browser_guid: other_guid)
get :index, params: { user_id: user2.id }
expect(response).to be_successful
returned_guids = response.parsed_body.map { |item| item["guid"] }
expect(returned_guids).to match_array([browser_guid2, browser_guid3])
expect(returned_guids).not_to include(browser_guid1)
expect(returned_guids).not_to include(other_guid)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/users/payout_infos_controller_spec.rb | spec/controllers/admin/users/payout_infos_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::PayoutInfosController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
before do
sign_in admin_user
end
describe "GET 'show'" do
it "returns the user's payout info as JSON" do
get :show, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body).to include("active_bank_account" => 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/admin/users/email_changes_controller_spec.rb | spec/controllers/admin/users/email_changes_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::EmailChangesController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user, email: "oldemail@example.com", payment_address: "old_address@example.com") }
before do
sign_in admin_user
end
describe "GET 'index'" do
context "when user has email and payment_address changes", versioning: true do
before do
user.update!(payment_address: "new_address@example.com")
user.update!(email: "newemail@example.com")
user.confirm
end
it "returns email changes and fields" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body).to match(
"email_changes" => [
{
"created_at" => an_instance_of(String),
"changes" => { "email" => ["oldemail@example.com", "newemail@example.com"] }
},
{
"created_at" => an_instance_of(String),
"changes" => { "payment_address" => ["old_address@example.com", "new_address@example.com"] }
},
{
"created_at" => an_instance_of(String),
"changes" => { "email" => ["", "oldemail@example.com"], "payment_address" => [nil, "old_address@example.com"] }
}
],
"fields" => ["email", "payment_address"]
)
end
end
context "when user has no changes" do
it "returns empty email changes" do
get :index, params: { user_id: user.id }, format: :json
expect(response).to have_http_status(:success)
expect(response.parsed_body).to eq(
"email_changes" => [],
"fields" => ["email", "payment_address"]
)
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/admin/users/products_controller_spec.rb | spec/controllers/admin/users/products_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::Users::ProductsController, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user) { create(:user) }
let!(:product1) { create(:product, user:) }
let!(:product2) { create(:product, user:) }
before do
sign_in admin_user
end
describe "GET index" do
before do
get :index, params: { user_id: user.id }
end
it "returns successful response with Inertia page data" do
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Users/Products/Index")
expect(inertia.props[:products]).to contain_exactly(hash_including(external_id: product1.external_id), hash_including(external_id: product2.external_id))
expect(inertia.props[:pagination]).to eq({ pages: 1, page: 1 })
end
context "when user has deleted products" do
let(:product2) { create(:product, user:, deleted_at: Time.current) }
it "includes deleted products in list" do
expect(inertia.props[:products]).to contain_exactly(hash_including(external_id: product1.external_id), hash_including(external_id: product2.external_id))
end
end
context "when user has banned products" do
let(:product2) { create(:product, user:, banned_at: Time.current) }
it "includes banned products in list" do
expect(inertia.props[:products]).to contain_exactly(hash_including(external_id: product1.external_id), hash_including(external_id: product2.external_id))
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/admin/users/products/tos_violation_flags_controller_spec.rb | spec/controllers/admin/users/products/tos_violation_flags_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
describe Admin::Users::Products::TosViolationFlagsController do
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
let(:user_risk_state) { :flagged_for_tos_violation }
let(:user) { create(:user, user_risk_state:) }
let(:product) { create(:product, user:) }
let(:tos_violation_flags) { create_list(:comment, 2, commentable: product, comment_type: Comment::COMMENT_TYPE_FLAGGED) }
before do
tos_violation_flags
sign_in admin_user
end
describe "GET index" do
it "returns a JSON payload with the tos violation flags" do
get :index, params: { user_id: user.id, product_external_id: product.external_id }
expect(response).to be_successful
payload = response.parsed_body
expect(payload["tos_violation_flags"]).to eq(tos_violation_flags.as_json(only: %i[id content]))
end
context "when the user is not flagged for TOS violation" do
let(:user_risk_state) { :compliant }
it "returns an empty array" do
get :index, params: { user_id: user.id, product_external_id: product.external_id }
expect(response).to be_successful
expect(response.parsed_body["tos_violation_flags"]).to eq([])
end
end
end
describe "POST create" do
let(:user_risk_state) { :compliant }
let(:suspend_tos_params) { { suspend_tos: { reason: "Spam content" } } }
context "when the user can be flagged for TOS violation" do
before do
allow_any_instance_of(User).to receive(:can_flag_for_tos_violation?).and_return(true)
end
it "flags the user for TOS violation and returns success" do
expect do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
end.to change { user.reload.tos_violation_reason }.from(nil).to("Spam content")
expect(response).to be_successful
expect(response.parsed_body["success"]).to be true
end
it "creates a comment for the TOS violation flag" do
expect do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
end.to change { Comment.count }.by(2)
comment = Comment.where(commentable: user).last
expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_FLAGGED)
expect(comment.content).to include("Flagged for a policy violation")
expect(comment.content).to include(product.name)
expect(comment.content).to include("Spam content")
comment = Comment.where(commentable: product).last
expect(comment.comment_type).to eq(Comment::COMMENT_TYPE_FLAGGED)
expect(comment.content).to include("Flagged for a policy violation")
expect(comment.content).to include(product.name)
expect(comment.content).to include("Spam content")
end
context "when the product is a tiered membership" do
let(:product) { create(:product, user:, is_tiered_membership: true) }
it "unpublishes the product" do
expect do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
end.to change { product.reload.published? }.from(true).to(false)
end
end
context "when the product is not a tiered membership" do
let(:product) { create(:product, user:, is_tiered_membership: false) }
it "deletes the product" do
expect do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
end.to change { product.reload.deleted? }.from(false).to(true)
end
end
end
context "when the user cannot be flagged for TOS violation" do
before do
allow_any_instance_of(User).to receive(:can_flag_for_tos_violation?).and_return(false)
end
it "returns an error" do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body["success"]).to be false
expect(response.parsed_body["error_message"]).to eq("Cannot flag for TOS violation")
end
end
context "when the reason is blank" do
let(:suspend_tos_params) { { suspend_tos: { reason: "" } } }
it "returns an error" do
post :create, params: { user_id: user.id, product_external_id: product.external_id }.merge(suspend_tos_params)
expect(response).to have_http_status(:bad_request)
expect(response.parsed_body["success"]).to be false
expect(response.parsed_body["error_message"]).to eq("Invalid 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/admin/search/users_controller_spec.rb | spec/controllers/admin/search/users_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::Search::UsersController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
let(:admin_user) { create(:admin_user) }
before do
sign_in admin_user
end
describe "GET index" do
let!(:john) { create(:user, name: "John Doe", email: "johnd@gmail.com") }
let!(:mary) { create(:user, name: "Mary Doe", email: "maryd@gmail.com", external_id: "12345") }
let!(:derek) { create(:user, name: "Derek Sivers", email: "derek@sive.rs") }
let!(:jane) { create(:user, name: "Jane Sivers", email: "jane@sive.rs") }
it "returns successful response with Inertia page data" do
get :index, params: { query: "Doe" }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Search/Users/Index")
end
it "returns JSON response when requested" do
get :index, params: { query: "Doe" }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([john.external_id, mary.external_id])
expect(response.parsed_body["pagination"]).to be_present
end
it "searches for users with partial email" do
get :index, params: { query: "sive.rs", format: :json }
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([derek.external_id, jane.external_id])
expect(response.parsed_body["pagination"]).to be_present
end
it "handles empty query" do
get :index, params: { query: "" }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([admin_user.external_id, john.external_id, mary.external_id, derek.external_id, jane.external_id])
expect(response.parsed_body["pagination"]).to be_present
end
it "paginates results" do
get :index, params: { query: "Doe", page: 1 }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["users"]).to be_present
expect(response.parsed_body["users"].map { |user| user["id"] }).to match_array([john.external_id, mary.external_id])
expect(response.parsed_body["pagination"]).to be_present
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/admin/search/purchases_controller_spec.rb | spec/controllers/admin/search/purchases_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "shared_examples/admin_base_controller_concern"
require "inertia_rails/rspec"
describe Admin::Search::PurchasesController, type: :controller, inertia: true do
render_views
it_behaves_like "inherits from Admin::BaseController"
before do
sign_in create(:admin_user)
end
describe "#index" do
let!(:email) { "user@example.com" }
let(:ip_v4) { "203.0.113.42" }
it "returns successful response with Inertia page data" do
get :index, params: { query: email }
expect(response).to be_successful
expect(inertia.component).to eq("Admin/Search/Purchases/Index")
end
it "returns JSON response when requested" do
purchase_1 = create(:purchase, email:, created_at: 3.seconds.ago)
purchase_2 = create(:purchase, email:, created_at: 2.seconds.ago)
purchase_3 = create(:purchase, email:, created_at: 1.second.ago)
get :index, params: { query: email, per_page: 2 }, format: :json
expect(response).to be_successful
expect(response.content_type).to match(%r{application/json})
expect(response.parsed_body["purchases"]).to contain_exactly(hash_including("external_id" => purchase_3.external_id), hash_including("external_id" => purchase_2.external_id))
expect(response.parsed_body["purchases"]).not_to include(hash_including("external_id" => purchase_1.external_id))
expect(response.parsed_body["pagination"]).to be_present
end
context "when transaction_date is invalid" do
let(:transaction_date) { "02/22" }
it "shows error flash message and no purchases" do
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: nil, product_title_query: nil).and_call_original
get :index, params: { transaction_date: "12/31" }
expect(flash[:alert]).to eq("Please enter the date using the MM/DD/YYYY format.")
end
end
it "redirects to the admin purchase page when one purchase is found" do
purchase_by_email = create(:purchase, email:)
purchase_by_ip = create(:purchase, ip_address: ip_v4)
get :index, params: { query: email }
expect(response).to redirect_to admin_purchase_path(purchase_by_email.external_id)
get :index, params: { query: ip_v4 }
expect(response).to redirect_to admin_purchase_path(purchase_by_ip.external_id)
end
it "returns purchases from AdminSearchService" do
purchase_1 = create(:purchase, email:)
purchase_2 = create(:gift, gifter_email: email, gifter_purchase: create(:purchase)).gifter_purchase
purchase_3 = create(:gift, giftee_email: email, giftee_purchase: create(:purchase)).giftee_purchase
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: email, product_title_query: nil).and_call_original
get :index, params: { query: email }
assert_response :success
expect(assigns(:purchases)).to include(purchase_1, purchase_2, purchase_3)
end
describe "product_title_query" do
let(:product_title_query) { "design" }
let!(:product) { create(:product, name: "Graphic Design Course") }
let!(:purchase) { create(:purchase, link: product, email: email) }
before do
create(:purchase, link: create(:product, name: "Different Product"))
end
context "when query is set" do
it "filters by product title" do
# Create another purchase with same email and same product to avoid redirect
create(:purchase, email: email, link: product)
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: email, product_title_query:).and_call_original
get :index, params: { query: email, product_title_query: product_title_query }
assert_response :success
expect(assigns(:purchases)).to include(purchase)
end
end
context "when query is not set" do
it "ignores product_title_query" do
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: "", product_title_query:).and_call_original
get :index, params: { query: "", product_title_query: product_title_query }
assert_response :success
expect(assigns(:purchases)).to include(purchase)
end
end
end
describe "purchase_status" do
let(:purchase_status) { "successful" }
let!(:successful_purchase) { create(:purchase, purchase_state: "successful", email: email) }
before do
create(:purchase, purchase_state: "failed", email: email)
end
context "when query is set" do
it "filters by purchase status" do
# Create another purchase with same email and same status to avoid redirect
create(:purchase, purchase_state: "successful", email: email)
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: email, product_title_query: nil, purchase_status:).and_call_original
get :index, params: { query: email, purchase_status: purchase_status }
assert_response :success
expect(assigns(:purchases)).to include(successful_purchase)
end
end
context "when query is not set" do
it "ignores purchase_status" do
expect_any_instance_of(AdminSearchService).to receive(:search_purchases).with(query: "", product_title_query: nil, purchase_status:).and_call_original
get :index, params: { query: "", purchase_status: purchase_status }
assert_response :success
expect(assigns(:purchases)).to include(successful_purchase)
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/help_center/categories_controller_spec.rb | spec/controllers/help_center/categories_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HelpCenter::CategoriesController do
describe "GET show" do
let(:category) { HelpCenter::Category.first }
context "render views" do
render_views
it "lists the category's articles and other categories for the same audience" do
get :show, params: { slug: category.slug }
expect(response).to have_http_status(:ok)
category.categories_for_same_audience.each do |c|
expect(response.body).to include(c.title)
end
category.articles.each do |a|
expect(response.body).to include(a.title)
end
end
end
context "when category is not found" do
it "redirects to the help center root path" do
get :show, params: { slug: "nonexistent-slug" }
expect(response).to redirect_to(help_center_root_path)
expect(response).to have_http_status(:found)
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/help_center/articles_controller_spec.rb | spec/controllers/help_center/articles_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe HelpCenter::ArticlesController do
describe "GET index" do
it "returns http success" do
get :index
expect(response).to have_http_status(:ok)
end
end
describe "GET show" do
let(:article) { HelpCenter::Article.find(43) }
it "returns http success" do
get :show, params: { slug: article.slug }
expect(response).to have_http_status(:ok)
end
context "render views" do
render_views
it "renders the article and categories for the same audience" do
get :show, params: { slug: article.slug }
expect(response).to have_http_status(:ok)
article.category.categories_for_same_audience.each do |c|
expect(response.body).to include(c.title)
end
expect(response.body).to include(article.title)
end
HelpCenter::Article.all.each do |article|
it "renders the article #{article.slug}" do
get :show, params: { slug: article.slug }
expect(response).to have_http_status(:ok)
expect(response.body).to include(ERB::Util.html_escape(article.title))
end
end
end
context "when article is not found" do
it "redirects to the help center root path" do
get :show, params: { slug: "nonexistent-slug" }
expect(response).to redirect_to(help_center_root_path)
expect(response).to have_http_status(:found)
end
end
context "when accessing the old jobs article URL" do
it "redirects to the about page jobs section with 301 status" do
get :show, params: { slug: "284-jobs-at-gumroad" }
expect(response).to redirect_to("/about#jobs")
expect(response).to have_http_status(:moved_permanently)
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/api/mobile/media_locations_controller_spec.rb | spec/controllers/api/mobile/media_locations_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Api::Mobile::MediaLocationsController do
describe "POST create" do
before do
@user = create(:user)
@purchaser = create(:user)
@url_redirect = create(:readable_url_redirect, link: create(:product, user: @user), purchase: create(:purchase, purchaser: @purchaser))
@purchase = @url_redirect.purchase
@product = @url_redirect.referenced_link
@product_file = @product.product_files.first
@app = create(:oauth_application, owner: @user)
@token = create("doorkeeper/access_token", application: @app, resource_owner_id: @purchaser.id, scopes: "mobile_api")
@mobile_post_params = { id: @purchase.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN, access_token: @token.token }
end
it "successfully creates media_location" do
media_location_params = {
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",
location: 1,
}
post :create, params: @mobile_post_params.merge(media_location_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(media_location_params[:platform])
expect(media_location.location).to eq(media_location_params[:location])
expect(media_location.unit).to eq MediaLocation::Unit::PAGE_NUMBER
expect(media_location.consumed_at).to eq(media_location_params[:consumed_at])
end
it "fails to create consumption event if access token is invalid" do
@mobile_post_params[:access_token] = "invalid_token"
media_location_params = {
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",
location: 1,
}
post :create, params: @mobile_post_params.merge(media_location_params)
expect(response.status).to be(401)
expect(MediaLocation.all.count).to eq(0)
end
it "fails to create consumption event if mobile token is invalid" do
@mobile_post_params[:mobile_token] = "invalid_token"
media_location_params = {
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",
location: 1,
}
post :create, params: @mobile_post_params.merge(media_location_params)
expect(response.status).to be(401)
expect(MediaLocation.all.count).to eq(0)
end
it "uses the url_redirect's purchase id if one is not provided" do
media_location_params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android",
location: 1,
}
post :create, params: @mobile_post_params.merge(media_location_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
media_location_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: @mobile_post_params.merge(media_location_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: "android", consumed_at: "2015-09-09T17:26:50PDT", location: 1)
expect(MediaLocation.count).to eq 1
media_location_params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android",
location: 2,
}
post :create, params: @mobile_post_params.merge(media_location_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(media_location_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-09T17:26:50PDT", location: 1)
expect(MediaLocation.count).to eq 1
media_location_params = {
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android",
location: 2,
}
post :create, params: @mobile_post_params.merge(media_location_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)
media_location_params = {
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",
location: 1,
}
post :create, params: @mobile_post_params.merge(media_location_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: "android", consumed_at: "2015-09-09T17:26:50PDT", location: 1)
params = {
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:24:50PDT",
location: 1,
}
post :create, params: @mobile_post_params.merge(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: "android", consumed_at: "2015-09-09T17:26:50PDT", location: 1)
params = {
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:28:50PDT",
location: 2,
}
post :create, params: @mobile_post_params.merge(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/api/mobile/base_controller_spec.rb | spec/controllers/api/mobile/base_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Api::Mobile::BaseController do
let(:application) { create(:oauth_application) }
let(:admin_user) { create(:admin_user) }
let(:access_token) do
create(
"doorkeeper/access_token",
application:,
resource_owner_id: admin_user.id,
scopes: "creator_api"
).token
end
let(:params) do
{
mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
access_token:
}
end
controller(Api::Mobile::BaseController) do
def index
head :ok
end
end
context "as admin user" do
let(:user) { create(:user) }
before do
@request.params["access_token"] = access_token
end
it "impersonates" do
controller.impersonate_user(user)
get(:index, params:)
expect(controller.current_resource_owner).to eq(user)
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/api/mobile/sessions_controller_spec.rb | spec/controllers/api/mobile/sessions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Api::Mobile::SessionsController, :vcr do
before do
@user = create(:user)
@app = create(:oauth_application, owner: @user)
@params = {
mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
access_token: create("doorkeeper/access_token", application: @app, resource_owner_id: @user.id, scopes: "mobile_api").token
}
end
describe "POST create" do
context "with valid credentials" do
it "signs in the user and responds with HTTP success" do
post :create, params: @params
expect(controller.current_user).to eq(@user)
expect(response).to be_successful
expect(response.parsed_body["success"]).to eq(true)
expect(response.parsed_body["user"]["email"]).to eq @user.email
end
end
context "with invalid credentials" do
it "responds with HTTP unauthorized" do
post :create, params: @params.merge(access_token: "invalid")
expect(response).to have_http_status(:unauthorized)
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/api/mobile/subscriptions_controller_spec.rb | spec/controllers/api/mobile/subscriptions_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "net/http"
describe Api::Mobile::SubscriptionsController, :vcr do
before do
@product = create(:subscription_product, user: create(:user))
@user = create(:user, credit_card: create(:credit_card))
@subscription = create(:subscription, link: @product, user: @user, created_at: 3.days.ago)
@purchase = create(:purchase, is_original_subscription_purchase: true, link: @product, subscription: @subscription, purchaser: @user)
@very_old_post = create(:installment, link: @product, created_at: 5.months.ago, published_at: 5.months.ago)
@old_post = create(:installment, link: @product, created_at: 4.months.ago, published_at: 4.months.ago)
@new_post = create(:installment, link: @product, published_at: Time.current)
@unpublished_post = create(:installment, link: @product, published_at: nil)
end
it "returns an error response for a dead subscription" do
@subscription.cancel_effective_immediately!
get :subscription_attributes, params: { id: @subscription.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN }
assert_response :not_found
expect(response.parsed_body).to eq({
success: false,
message: "Could not find subscription"
}.as_json)
end
it "returns the correct information if the subscription is still alive" do
get :subscription_attributes, params: { id: @subscription.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN }
assert_response 200
expect(response.parsed_body).to eq({ success: true, subscription: @subscription.subscription_mobile_json_data }.as_json)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/spec/controllers/api/mobile/consumption_analytics_controller_spec.rb | spec/controllers/api/mobile/consumption_analytics_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Api::Mobile::ConsumptionAnalyticsController do
describe "POST create" do
before do
@user = create(:user)
@purchaser = create(:user)
@url_redirect = create(:readable_url_redirect, link: create(:product, user: @user), purchase: create(:purchase, purchaser: @purchaser))
@purchase = @url_redirect.purchase
@product = @url_redirect.referenced_link
@product_file = @product.product_files.first
@app = create(:oauth_application, owner: @user)
@token = create("doorkeeper/access_token", application: @app, resource_owner_id: @purchaser.id, scopes: "mobile_api")
@mobile_post_params = { id: @purchase.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN, access_token: @token.token }
@purchaseless_url_redirect = create(:readable_url_redirect, link: @product, purchase: nil)
end
it "successfully creates consumption event" do
consumption_event_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: @mobile_post_params.merge(consumption_event_params)
expect(response.parsed_body["success"]).to be(true)
event = ConsumptionEvent.last
expect(event.event_type).to eq(consumption_event_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(@product.id)
expect(event.platform).to eq(consumption_event_params[:platform])
expect(event.consumed_at).to eq(consumption_event_params[:consumed_at])
end
it "fails to create consumption event if access token is invalid" do
@mobile_post_params[:access_token] = "invalid_token"
consumption_event_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: @mobile_post_params.merge(consumption_event_params)
expect(response.status).to be(401)
expect(ConsumptionEvent.all.count).to eq(0)
end
it "fails to create consumption event if mobile token is invalid" do
@mobile_post_params[:mobile_token] = "invalid_token"
consumption_event_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: @mobile_post_params.merge(consumption_event_params)
expect(response.status).to be(401)
expect(ConsumptionEvent.all.count).to eq(0)
end
it "uses the url_redirect's purchase id if one is not provided" do
consumption_event_params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @url_redirect.external_id,
platform: "android"
}
post :create, params: @mobile_post_params.merge(consumption_event_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
consumption_event_params = {
event_type: "read",
product_file_id: @product_file.external_id,
url_redirect_id: @purchaseless_url_redirect.external_id,
platform: "android"
}
post :create, params: @mobile_post_params.merge(consumption_event_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
consumption_event_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: @mobile_post_params.merge(consumption_event_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
consumption_event_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: "android"
}
post :create, params: @mobile_post_params.merge(consumption_event_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/api/mobile/installments_controller_spec.rb | spec/controllers/api/mobile/installments_controller_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Api::Mobile::InstallmentsController do
before do
@product = create(:subscription_product, user: create(:user))
@post = create(:installment, link: @product, published_at: Time.current)
@follower = create(:follower)
end
it "returns an error response for a unknown installment" do
get :show, params: { id: "xxx", mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN }
assert_response :not_found
expect(response.parsed_body).to eq({
success: false,
message: "Could not find installment"
}.as_json)
end
it "returns the correct information if installment is available" do
get :show, params: { id: @post.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN, follower_id: @follower.external_id }
assert_response :success
expect(response.parsed_body).to eq({ success: true, installment: @post.installment_mobile_json_data(follower: @follower) }.as_json)
end
it "returns error if none of purchase, subscription, or followers is provided" do
get :show, params: { id: @post.external_id, mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN }
assert_response :not_found
expect(response.parsed_body).to eq({
success: false,
message: "Could not find related object to the installment."
}.as_json)
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.