How to A/B test prices in Rails

Price testing in Rails 8: write the visitor cookie on Rack 2 or 3, keep Turbo out of the Stripe redirect, charge the tested price and verify the revenue.

Short answer

Add the leverprice gem, create one client in an initializer, call get_price in the controller that renders the price and pass the quote to Leverprice.write_cookies(response, quote). At checkout, price again, send quote.price and the whole quote.metadata to Stripe Checkout, and redirect with allow_other_host: true from a form that has Turbo turned off.

  • Leverprice.write_cookies appends Set-Cookie values in the shape your Rack version expects: newline-joined on Rack 2, an array on Rack 3.
  • Turbo submits forms with fetch(), so a redirect to Stripe Checkout fails on CORS unless the checkout form has data-turbo set to false.
  • Turbo 8 prefetches links on hover with an X-Sec-Purpose header, so turn prefetching off for links to the pricing page.
  • redirect_to guards against other hosts; pass allow_other_host: true for the Stripe URL, which comes from Stripe's API.

Two Turbo defaults and one Rails safety check stand between a Rails app and a working price test. Turbo Drive submits the checkout form with fetch(), so the redirect to Stripe dies on CORS; Turbo 8 requests the pricing page when a visitor merely hovers a link to it; and redirect_to refuses to send anyone to another host. Each fix is one attribute or one option, and this guide shows where each goes.

The code targets Rails 8.1 on Rack 3, turbo-rails 2, stripe-ruby 21 and the leverprice gem, which runs on Ruby 3.1+.

How does price testing work in a Rails app?

Your server decides the price. get_price reads the visitor's __pp cookie and user agent from the ActionDispatch::Request, picks their price from a signed config held in memory, checks it against bounds you set in code and returns a quote: price in minor units (2900 is $29.00), currency, signed metadata and an array of Set-Cookie values. No Leverprice JavaScript runs in the browser.

The checkout action calls get_price again and gets the same answer, because the signed cookie comes back with the browser. Stripe later confirms the payment to Leverprice with a signed webhook, and traffic shifts toward the price that earns the most per visitor. The reasoning for doing all this on the server is in server-side price testing.

How do I install the gem in Rails?

Terminal
bundle add leverprice stripe

Set LEVERPRICE_SECRET_KEY (pp_sk_test_… locally) and STRIPE_SECRET_KEY in the environment, then create one client at boot:

config/initializers/leverprice.rb
LEVERPRICE = Leverprice::Client.new(
  secret_key: ENV["LEVERPRICE_SECRET_KEY"],
  products: {
    # Guardrails in minor units: a price outside them is never returned.
    "pro" => { currency: "usd", fallback_price: 2900, min_price: 1900, max_price: 4900 },
  },
  logger: Rails.logger,
)
LEVERPRICE.preload
at_exit { LEVERPRICE.close }

Create the Stripe client in the controller, not here. Rails' generated Dockerfile runs SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile, which loads initializers without your secrets, and Stripe::StripeClient.new(nil) raises. A Leverprice client without a key doesn't raise; it serves your fallback price and makes no network calls.

fallback_price is what visitors pay when Leverprice cannot answer: no key, LEVERPRICE_DISABLED=1, or no signed config within 500 ms. get_price raises only for a product key missing from products. The full option list is in the SDK docs.

How do I show the tested price in a Rails controller?

app/controllers/pricing_controller.rb
class PricingController < ApplicationController
  def show
    @quote = LEVERPRICE.get_price("pro", request: request, user_id: current_user&.id)
    Leverprice.write_cookies(response, @quote)
  end
end
app/views/pricing/show.html.erb
<p class="price"><%= format("%.2f", @quote.price / 100.0) %> <%= @quote.currency.upcase %></p>
<%= button_to "Buy Pro", checkout_path, form: { "data-turbo" => "false" } %>
config/routes.rb
get "pricing", to: "pricing#show"
resource :checkout, only: :create
post "webhooks/stripe", to: "stripe_webhooks#create"

Write the cookies with Leverprice.write_cookies, not the cookies jar. The SDK hands you finished header lines, attributes included, and cookies.signed or cookies.encrypted would wrap the value in a second signature the SDK cannot verify. The helper also handles the Rack split: Rack 2 joins several Set-Cookie values with newlines, while the Rack 3 spec requires an array and forbids newlines in header values. Writing the header by hand works on one and breaks on the other.

user_id (here current_user from Devise or your own auth) puts a signed-in customer in the same bucket on every device, and only an HMAC of it leaves your server. Pass it the same way wherever you price the product.

Why does Turbo prefetch skew a Rails price test?

Since Turbo 8, prefetching links on hover is on by default, per the Turbo handbook. The prefetch is a real GET to your pricing action, sent with an X-Sec-Purpose: prefetch header (Turbo source). The SDK prices prefetches without counting them only when it sees Sec-Purpose, Purpose, X-Purpose, X-Moz or Next-Router-Prefetch, so a visitor who hovers your Pricing link and moves on is logged as having seen a price.

Turn prefetching off for links to the pricing page:

app/views/layouts/_nav.html.erb
<%= link_to "Pricing", pricing_path, data: { turbo_prefetch: false } %>

Or add <meta name="turbo-prefetch" content="false"> to the layout to switch it off everywhere. A click then fetches the page without the prefetch header, so the exposure is counted only when a visitor actually asked for the page.

How do I charge the same price with Stripe Checkout?

Price the checkout on the server again and ignore any amount in the params. Stripe's price_data takes the amount inline, so there is no Stripe Price per tested price:

app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def create
    quote = LEVERPRICE.get_price("pro", request: request, user_id: current_user&.id)
    Leverprice.write_cookies(response, quote)
    checkout_session = stripe.v1.checkout.sessions.create({
      mode: "payment",
      line_items: [{
        quantity: 1,
        price_data: { currency: quote.currency, unit_amount: quote.price, product_data: { name: "Pro" } },
      }],
      metadata: quote.metadata, # signed attribution: pass it whole
      payment_intent_data: { metadata: quote.metadata },
      success_url: root_url,
      cancel_url: pricing_url,
    })
    redirect_to checkout_session.url, allow_other_host: true, status: :see_other
  end

  private

  def stripe
    Stripe::StripeClient.new(ENV.fetch("STRIPE_SECRET_KEY"))
  end
end

Rails guards against open redirects, and the redirect_to docs say allow_other_host: true permits one, with a warning that a user-provided param is unsafe there. The Stripe URL comes from Stripe's API, so it is fine. status: :see_other sends a 303, so the browser follows the POST with a GET.

The data-turbo="false" on the form is the other half. Turbo sends form submissions with fetch(), and following a redirect to checkout.stripe.com from there fails on CORS, as reported in turbo-rails issue 483. With Turbo off for that form, the browser submits it normally and follows the redirect.

button_to includes the authenticity token, so CSRF protection stays on. Name the Stripe object checkout_session so it doesn't shadow Rails' session.

Selling a subscription? Use mode: "subscription", add recurring: { interval: "month" } to price_data, and move the metadata copy into subscription_data, because the Checkout Session API accepts payment_intent_data only in payment mode. Leverprice's Stripe verification covers one-time payments, so report a subscription's first payment with track_purchase from your own webhook controller; it shows as unverified, and renewals never count toward a test.

Other providers take the same two rules: charge quote.price, pass quote.metadata whole. Polar accepts an ad-hoc price per checkout, and Leverprice verifies one-time orders and a subscription's first payment there. Lemon Squeezy takes custom_price in cents but stops processing payments on March 31, 2027. Dodo Payments takes a custom amount only on pay-what-you-want products, with one-time payments verified.

Can I show a different price per country?

Yes. With regional prices on in the dashboard, each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), in its own currency. Example: ₹999 for a visitor in India, $29 in the US. The initializer decides where the country comes from and which prices may pass:

config/initializers/leverprice.rb
LEVERPRICE = Leverprice::Client.new(
  secret_key: ENV["LEVERPRICE_SECRET_KEY"],
  country_header: "cf-ipcountry", # set by Cloudflare; CloudFront: cloudfront-viewer-country
  products: {
    "pro" => {
      currency: "usd", fallback_price: 2900, min_price: 1900, max_price: 4900,
      regional: { # currencies you accept, each with hard bounds
        usd: { min_price: 800, max_price: 4900 },
        eur: { min_price: 1100, max_price: 6000 },
        inr: { min_price: 48_000, max_price: 230_000 },
      },
    },
  },
  logger: Rails.logger,
)

country_header: takes the HTTP header name, not the Rack key; the SDK finds HTTP_CF_IPCOUNTRY itself. It has no default, because a header visitors can send themselves would let them choose their price. Without a CDN header, pass country: from your own GeoIP lookup. Unlisted currencies, prices outside their bounds, bots and unknown countries get the standard price.

The checkout already passes quote.currency, so Stripe charges in the visitor's currency; confirm your account supports each one. The view's / 100.0 fits two-decimal currencies only. JPY has no minor unit, per Stripe's zero-decimal list.

How does Leverprice verify revenue from Stripe?

Stripe sends signed webhooks to Leverprice directly. In the dashboard, open Payments and connect Stripe to get an endpoint URL. Add it in Stripe for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste the endpoint's signing secret into Leverprice.

Stripe confirms each purchase to Leverprice with a webhook signed by the endpoint's secret.

A signing secret can confirm events but cannot move money, so an API key never goes there. The Stripe integration page has the details. Write your own controller only if you cannot add an endpoint or you sell subscriptions; its revenue is labeled unverified and never overrides a verified purchase:

app/controllers/stripe_webhooks_controller.rb
class StripeWebhooksController < ActionController::API
  PAID = %w[checkout.session.completed checkout.session.async_payment_succeeded].freeze

  def create
    event = Stripe::Webhook.construct_event(
      request.raw_post, request.headers["Stripe-Signature"], ENV.fetch("STRIPE_WEBHOOK_SECRET"),
    )
    if PAID.include?(event.type) && event.data.object.payment_status == "paid"
      checkout = event.data.object
      LEVERPRICE.track_purchase(
        provider: "stripe",
        order_id: checkout.payment_intent || checkout.invoice, # invoice: subscription mode
        amount: checkout.amount_total - (checkout.total_details&.amount_tax || 0),
        currency: checkout.currency,
        metadata: checkout.metadata.to_h,
        timestamp: event.created,
      )
    end
    head :ok
  rescue JSON::ParserError, Stripe::SignatureVerificationError
    head :bad_request
  end
end

ActionController::API leaves out forgery protection, so Stripe's POST isn't rejected for a missing token; in an ApplicationController subclass, call skip_forgery_protection. Verify request.raw_post, the exact bytes Stripe signed.

How do I test it locally?

Run bin/dev with test keys, connect a test-mode Stripe endpoint in Leverprice, and open http://localhost:3000/pricing:

  1. Note the price and reload. It must not change.
  2. Click Buy and compare Stripe's amount with the page. Pay with a card from Stripe's testing docs, such as 4242 4242 4242 4242.
  3. Unset LEVERPRICE_SECRET_KEY, restart, reload: the fallback price appears with reason "disabled".

System tests deserve a note. Rails' default ApplicationSystemTestCase drives Chrome with using: :headless_chrome, and headless browsers count as bots, so those tests always see the standard price with reason "bot". Pass disabled: true to the client in the test environment, as the gem's README suggests, or pass bot: false to get_price under Rails.env.test? when a test needs a tested price. Over plain HTTP on a LAN address, set cookie_secure: false in development; MDN documents the HTTPS exception only for localhost.

What changes in production?

Swap in pp_sk_live_… and your live Stripe key, and connect the live-mode Stripe endpoint in Leverprice with its own signing secret. With Kamal, list the keys under env.secret in config/deploy.yml and supply them through .kamal/secrets, as the Kamal docs show.

Clustered Puma with preload_app! boots the app once, so the preload call in the initializer gives every worker a verified config. The gem detects the fork and gives each worker its own threads, locks and event queue. Keep the pricing action out of HTTP caches: no expires_in ..., public: true and no CDN caching for that page. LEVERPRICE_DISABLED=1 plus a restart sends every visitor your fallback price.

What breaks most often?

SymptomLikely causeFix
CORS error in the console after clicking BuyTurbo followed the redirect to Stripe with fetch()form: { "data-turbo" => "false" } on button_to
UnsafeRedirectError, or an open-redirect warning in the logredirect_to to Stripe without permissionallow_other_host: true
Exposures higher than real page viewsTurbo hover prefetchdata: { turbo_prefetch: false } on pricing links
Docker build fails at assets:precompileA Stripe client built in an initializer without its keyCreate it in the controller
Cookie lost or malformed after moving to Rack 3Set-Cookie written by hand in the Rack 2 shapeLeverprice.write_cookies(response, quote)
System tests always show the standard priceHeadless Chrome counts as a botdisabled: true in tests, or bot: false
422 on your own Stripe webhookForgery protection on the webhook controllerActionController::API or skip_forgery_protection

Frequently asked questions

Does this work with Sinatra or plain Rack?

Yes. get_price(request:) accepts a Rack env Hash or any request object, and Leverprice.write_cookies writes to a Sinatra response or a Rack headers Hash. allow_other_host is Rails-only, and the Turbo notes apply only where Turbo runs.

How do I price monthly and yearly plans on one page?

Give each plan its own product key, call get_price for both with the same request, and write both quotes' cookies. They share one visitor, and the last cookie carries every assignment.

Can a Rails checkout share visitors with a Next.js front end?

Yes, when both run with keys from the same Leverprice project. Every SDK passes the same conformance tests, so a cookie written by the JavaScript SDK is read by the gem; if the apps run on different subdomains, set the same cookie_domain on both. The front-end side is in the Next.js guide.

What happens when the test ends?

You lock in the winner in the dashboard, and every visitor gets it within about a second. The Rails code doesn't change.