Intermediate TDD in Rails : Create a Stripe Customer

Objective


To create a Stripe customer in our Stripe account.

Discussion


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.

Steps


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'
end

Step 3

Run the test. We get the error:

uninitialized constant StripeGateway (NameError)

Step 4

Create an empty class:

class StripeGateway
end

Run the test.

Step 5

Change the test:

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

  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(token.id, 'description')

    expect(customer.id.size).to be > 2 
  end

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)
  end

end

Run the test. The test passes.

Summary


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


Related Articles


Create your own user feedback survey