Hidden gems: fake_braintree

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

And in your spec/spec_helper.rb:

require 'fake_braintree'
RSpec.configure do |config|
config.before do
FakeBraintree.clear!
end
end

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
end
it 'fails when the card is declined' do
FakeBraintree.decline_all_cards!
expect { transact }.to raise_error
end
def transact
Purchase.new.transact
end
end

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.