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.
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
end
end
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!