Skip to content

Instantly share code, notes, and snippets.

@d1rtyvans
Created June 15, 2016 16:07
Show Gist options
  • Save d1rtyvans/a836eaa84f8ae5881b1ba6bd325d9986 to your computer and use it in GitHub Desktop.
Save d1rtyvans/a836eaa84f8ae5881b1ba6bd325d9986 to your computer and use it in GitHub Desktop.
require "rails_helper"
RSpec.describe StripeCharger do
describe "#create_charge" do
context "if the user does not have a stripe_id" do
it "creates a charge and a stripe customer" do
user = create(:user, stripe_id: nil)
order = create(:order, user: user)
add_to_cart(order: order, meal: create(:meal))
stub_charge
stub_create_customer
StripeCharger.new(
email: user.email,
order: order,
token: "THISISATOKEN",
).create_charge
expect_charge_to_be_created(order: order)
expect(Stripe::Customer).to have_received(:create).with(
email: user.email,
source: "THISISATOKEN",
)
end
end
context "if the user already has a stripe_id" do
it "retreives a stripe customer and creates a charge if customer exists" do
user = create(:user, stripe_id: "THISISATOKEN")
order = create(:order, user: user)
add_to_cart(order: order, meal: create(:meal))
stub_charge
retrieved_customer = stub_retrieve_customer
StripeCharger.new(
email: user.email,
order: order,
token: "SUPBRASKI",
).create_charge
expect_charge_to_be_created(order: order)
expect(Stripe::Customer).to have_received(:retrieve).with(user.stripe_id)
expect(retrieved_customer).to have_received("source=").with("SUPBRASKI")
expect(retrieved_customer).to have_received(:save)
end
end
context "if the order is free" do
it "does not contact stripe at all" do
order = create(:order)
stub_charge
stub_retrieve_customer
stub_create_customer
StripeCharger.new(
email: order.user.email,
order: order,
token: "SUPBRASKI",
).create_charge
expect(Stripe::Charge).to_not have_received(:create)
expect(Stripe::Customer).to_not have_received(:create)
expect(Stripe::Customer).to_not have_received(:retrieve)
end
end
end
def add_to_cart(meal:, order:)
order.add(meal: create(:cart_item, meal: meal))
end
def stub_charge
allow(Stripe::Charge).to receive(:create)
end
def stub_create_customer
allow(Stripe::Customer).to receive(:create).and_return(stripe_customer)
end
def stub_retrieve_customer
stripe_customer.tap do |sc|
allow(Stripe::Customer).to receive(:retrieve).and_return(sc)
end
end
def stripe_customer
double("Stripe::Customer", id: "THISISATOKEN").tap do |sc|
allow(sc).to receive("source=")
allow(sc).to receive(:save)
end
end
def expect_charge_to_be_created(order:)
expect(Stripe::Charge).to have_received(:create).with(
customer: order.user.reload.stripe_id,
amount: order.total,
currency: "usd",
description: "HomeCookin' Meal",
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment