Intermediate TDD in Rails : Create a Stripe Customer


To create a Stripe customer in our Stripe account.


Before we interact with our external API. We need to make sure that our Stripe API library version is set properly. All the features we will develop is based on Stripe API Version = 2015-02-18. So the initialization code config/initializers/stripe.rb must provide the api_key and the api_version like this:

Stripe.api_key = 'sk_test_watHqWl2XD88WHqhknk7sqXN'
Stripe.api_version = "2015-02-18"

This is important because sometimes the newer versions will have incompatible changes and we may need to revert back to older version of the library.


Step 1

Create a spec/gateway and app/gateway folders. All the code that deals with external services will be in this directory. Gateway is an object that encapsulates access to an external system. You can read more about the Gateway Pattern on Martin Fowler's site.

Step 2

The spec/gateway/stripe_gateway_spec.rb looks like this:

require 'rails_helper'
require 'spec_helper'

describe StripeGateway do

  it 'should create a customer'
  it 'should subscribe a customer to a given plan'

Step 3

Run the test. We get the error:

uninitialized constant StripeGateway (NameError)

Step 4

Create an empty class:

class StripeGateway

Run the test.

Step 5

Change the test:

  before do
    Stripe.api_key = 'sk_test_watHqWl2XD88WHqhknk7sqXN'
    Stripe.api_version = "2015-02-18"

  it 'should create a customer' do
    token = Stripe::Token.create(
      card: {
        number: "4242424242424242",
        exp_month: 3,
        exp_year: 2016,
        cvc: "314"

    customer = StripeGateway.create_customer(, 'description')

    expect( be > 2 

Step 6

Run the test. We get the error:

undefined method `create_customer' for StripeGateway:Class

Step 7

Implement the method as follows:

class StripeGateway

  def self.create_customer(token, description)
    Stripe::Customer.create(description: description,  source: token)


Run the test. The test passes.


In this lesson, we implemented a method that creates a Stripe customer object in our Stripe account.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.