April 20, 2015 / admin

If you’re using Stripe in your application you’ll want to create some integration and/or acceptance tests that actually interact with your Stripe account. So how do you go about doing so?

Fortunately Stripe provides pretty good support for testing. First, when you create an account you get two sets of keys: one for production and one for testing. So in your development environment you configure your app to use the test key (via environment variable or however you set configuration info for your environments). Then when you deploy the app to production, you simply change the value to use the production key. That’s it. You don’t need to change anything in your code.

Second, Stripe provides a significant set of test credit card numbers that represent different card types and card numbers that will cause Stripe to provide specific responses. For example there is a specific card number that when used will cause Stripe to send back a response that the card had expired. See https://stripe.com/docs/testing for more info.

There is one issue you must be aware of when testing with Stripe – your Stripe account has state. What this means for testing is that once a test is complete, what ever was changed in your account, remains that way. If you’re familiar with testing with databases you’ll be very familiar with the issues this can cause.

For any test to properly run and actually test what you expect, the test must run with the part of the application that is under test, to be in a known state.

Say you have two tests (testA and testB) that interact with your Stripe account and both tests expect a given customer to not have any discounts. And say testB adds a discount to that customer. Therefore after testB is executed, Stripe will still have a discount associated to that customer.

Because of state we’ve broken the independence between the two tests. On the first execution of the tests, if testA executes before testB then both test will pass. If testB should run before testA, testA fill fail. If the tests are subsequently run, both tests would fail.

So how can we make these tests independent? If these were the only tests, you could have each test work with a different customer. Then add another customer for each new test. However, as the number of tests increase, this solution can quickly become a quagmire.

Another solution is to place Stripe into a known state before each test. In my next blog post I’ll describe how I went about creating a way to fairly easily do so in a repeatable way.

Posted In: Blog, Programming