Hidden gems: fake_braintree

Mike Burns

The fake_braintree gem makes your life easier when testing code that charges credit cards. It is a fake Braintree server that can be manipulated as you see fit.

Start by installing fake_braintree. In your Gemfile:

gem 'braintree'

group :test do
  gem 'fake_braintree'

And in your spec/spec_helper.rb:

require 'fake_braintree'

RSpec.configure do |config|
  config.before do

That RSpec configuration clears the fake data between test runs.

Now we can write a quick spec for Purchase#transact:

require 'spec_helper'

describe Purchase do
  it 'charges successfully' do
    transact.should be_true

  it 'fails when the card is declined' do
    expect { transact }.to raise_error

  def transact

You can see fake_braintree peeking through there in the second spec, where we decline all credit card transactions. Since we clear fake data between test runs, this does not affect other tests.

We can make this pass as normal:

class Purchase
  def transact
    result = Braintree::Transaction.sale(
      amount: '1000.00',
      credit_card:  {
        number: '5105105105105100',
        expiration_date: '05/12'

    result.success? or raise result.errors.inspect

That was easy

The fake_braintree gem is basically invisible until you need it. The Braintree implementation code is unchanged, and the success paths are the default.

You can set fake_braintree to verify or outright decline credit cards (as above), and you can also generate transactions as if the user really did buy something.

So stop being so hands-on with your credit card mocking and stubbing and give fake_braintree a try today!

author image
Mike Burns
Sign up to receive a weekly recap from GIANT ROBOTS