https://github.com/andrew/stripe-ruby-mock

A mocking library for testing stripe ruby

https://github.com/andrew/stripe-ruby-mock

Science Score: 10.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    1 of 62 committers (1.6%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (12.2%) to scientific vocabulary
Last synced: 10 months ago · JSON representation

Repository

A mocking library for testing stripe ruby

Basic Info
  • Host: GitHub
  • Owner: andrew
  • License: mit
  • Language: Ruby
  • Default Branch: master
  • Homepage:
  • Size: 740 KB
Statistics
  • Stars: 0
  • Watchers: 1
  • Forks: 1
  • Open Issues: 0
  • Releases: 0
Fork of stripe-ruby-mock/stripe-ruby-mock
Created almost 11 years ago · Last pushed almost 11 years ago
Metadata Files
Readme Changelog License

README.md

stripe-ruby-mock Build Status Gitter chat

  • Homepage: https://github.com/rebelidealist/stripe-ruby-mock
  • Issues: https://github.com/rebelidealist/stripe-ruby-mock/issues
  • CHAT: https://gitter.im/rebelidealist/stripe-ruby-mock

REQUEST: Looking for More Core Contributors

This gem has unexpectedly grown in popularity and I've gotten pretty busy, so I'm currently looking for more core contributors to help me out. If you're interested, there is only one requirement: submit a significant enough pull request and have it merged into master (many of you have already done this). Afterwards, ping me in chat and I will add you as a collaborator.

Install

In your gemfile:

gem 'stripe-ruby-mock', '~> 2.1.1', :require => 'stripe_mock'

Features

  • No stripe server access required
  • Easily test against stripe errors
  • Mock and customize stripe webhooks
  • Flip a switch to run your tests against Stripe's live test servers

Specifications

STRIPE API TARGET VERSION: 2015-02-18 (master)

Older API version branches:

Versioning System

Since StripeMock tries to keep up with Stripe's API version, its version system is a little different:

  • The major number (1.x.x) is for breaking changes involving how you use StripeMock itself
  • The minor number (x.1.x) is for breaking changes involving Stripe's API
  • The patch number (x.x.0) is for non-breaking changes/fixes involving Stripe's API, or for non-breaking changes/fixes/features for StripeMock itself.

Description

** WARNING: This library does not cover all Stripe API endpoints. If you need one that's missing, please create an issue for it, or see this wiki page if you're interested in contributing **

At its core, this library overrides stripe-ruby's request method to skip all http calls and instead directly return test data. This allows you to write and run tests without the need to actually hit stripe's servers.

You can use stripe-ruby-mock with any ruby testing library. Here's a quick dummy example with RSpec:

```ruby require 'stripe_mock'

describe MyApp do let(:stripehelper) { StripeMock.createtest_helper } before { StripeMock.start } after { StripeMock.stop }

it "creates a stripe customer" do

# This doesn't touch stripe's servers nor the internet!
# Specify :source in place of :card (with same value) to return customer with source data
customer = Stripe::Customer.create({
  email: 'johnny@appleseed.com',
  card: stripe_helper.generate_card_token
})
expect(customer.email).to eq('johnny@appleseed.com')

end end ```

Test Helpers

Some Stripe API calls require several parameters. StripeMock helps you keep your test brief with some helpers:

```ruby describe MyApp do let(:stripehelper) { StripeMock.createtest_helper }

it "creates a stripe plan" do plan = stripehelper.createplan(:id => 'my_plan', :amount => 1500)

# The above line replaces the following:
# plan = Stripe::Plan.create(
#   :id => 'my_plan',
#   :name => 'StripeMock Default Plan ID',
#   :amount => 1500,
#   :currency => 'usd',
#   :interval => 'month'
# )
expect(plan.id).to eq('my_plan')
expect(plan.amount).to eq(1500)

end end ```

The available helpers are:

ruby stripe_helper.create_plan(my_plan_params) stripe_helper.delete_plan(my_plan_params) stripe_helper.generate_card_token(my_card_params)

For everything else, use Stripe as you normally would (i.e. use Stripe as if you were not using StripeMock).

Live Testing

Every once in a while you want to make sure your tests are actually valid. StripeMock has a switch that allows you to run your test suite (or a subset thereof) against Stripe's live test servers.

Here is an example of setting up your RSpec (2.x) test suite to run live with a command line switch:

```ruby

RSpec 2.x

RSpec.configure do |c| if c.filtermanager.inclusions.keys.include?(:live) StripeMock.togglelive(true) puts "Running live tests against Stripe..." end end ```

With this you can run live tests by running rspec -t live

Here is an example of setting up your RSpec (3.x) test suite to run live with the same command line switch:

```ruby

RSpec 3.x

RSpec.configure do |c| if c.filtermanager.inclusions.rules.include?(:live) StripeMock.togglelive(true) puts "Running live tests against Stripe..." end end ```

Mocking Card Errors

Tired of manually inputting fake credit card numbers to test against errors? Tire no more!

```ruby it "mocks a declined card error" do # Prepares an error for the next create charge request StripeMock.preparecarderror(:card_declined)

expect { Stripe::Charge.create(amount: 1, currency: 'usd') }.to raiseerror {|e| expect(e).to bea Stripe::CardError expect(e.httpstatus).to eq(402) expect(e.code).to eq('carddeclined') } end ```

Built-In Card Errors

ruby StripeMock.prepare_card_error(:incorrect_number) StripeMock.prepare_card_error(:invalid_number) StripeMock.prepare_card_error(:invalid_expiry_month) StripeMock.prepare_card_error(:invalid_expiry_year) StripeMock.prepare_card_error(:invalid_cvc) StripeMock.prepare_card_error(:expired_card) StripeMock.prepare_card_error(:incorrect_cvc) StripeMock.prepare_card_error(:card_declined) StripeMock.prepare_card_error(:missing) StripeMock.prepare_card_error(:processing_error)

You can see the details of each error in lib/stripe_mock/api/errors.rb

Specifying Card Errors

By default, prepare_card_error only triggers for :new_charge, the event that happens when you run Charge.create. More explicitly, this is what happens by default:

ruby StripeMock.prepare_card_error(:card_declined, :new_charge)

If you want the error to trigger on a different event, you need to replace :new_charge with a different event. For example:

```ruby StripeMock.preparecarderror(:carddeclined, :createcard) customer = Stripe::Customer.create

This line throws the card error

customer.cards.create ```

:new_charge and :create_card are names of methods in the StripeMock request handlers. You can also set StripeMock.toggle_debug(true) to see the event name for each Stripe request made in your tests.

Custom Errors

To raise an error on a specific type of request, take a look at the request handlers folder and pass a method name to StripeMock.prepare_error.

If you wanted to raise an error for creating a new customer, for instance, you would do the following:

```ruby it "raises a custom error for specific actions" do custom_error = StandardError.new("Please knock first.")

StripeMock.prepareerror(customerror, :new_customer)

expect { Stripe::Charge.create(amount: 1, currency: 'usd') }.tonot raiseerror expect { Stripe::Customer.create }.to raiseerror {|e| expect(e).to bea StandardError expect(e.message).to eq("Please knock first.") } end ```

In the above example, :new_customer is the name of a method from customers.rb.

Running the Mock Server

Sometimes you want your test stripe data to persist for a bit, such as during integration tests running on different processes. In such cases you'll want to start the stripe mock server:

# spec_helper.rb
#
# The mock server will automatically be killed when your tests are done running.
#
require 'thin'
StripeMock.spawn_server

Then, instead of StripeMock.start, you'll want to use StripeMock.start_client:

```ruby describe MyApp do before do @client = StripeMock.start_client end

after do StripeMock.stopclient # Alternatively: # @client.close! # -- Or -- # StripeMock.stopclient(:clearserverdata => true) end end ```

This is all essentially the same as using StripeMock.start, except that the stripe test data is held in its own server process.

Here are some other neat things you can do with the client:

```ruby @client.state #=> 'ready'

@client.getserverdata(:customers) # Also works for :charges, :plans, etc. @client.clearserverdata

@client.close! @client.state #=> 'closed' ```

Mock Server Options

```ruby

NOTE: Shown below are the default options

StripeMock.defaultserverpid_path = './stripe-mock-server.pid'

StripeMock.spawnserver( :pidpath => StripeMock.defaultserverpid_path, :host => '0.0.0.0', :port => 4999, :server => :thin )

StripeMock.killserver(StripeMock.defaultserverpidpath) ```

Mock Server Command

If you need the mock server to continue running even after your tests are done, you'll want to use the executable:

$ stripe-mock-server -p 4000
$ stripe-mock-server --help

Mocking Webhooks

If your application handles stripe webhooks, you are most likely retrieving the event from stripe and passing the result to a handler. StripeMock helps you by easily mocking that event:

```ruby it "mocks a stripe webhook" do event = StripeMock.mockwebhookevent('customer.created')

customerobject = event.data.object expect(customerobject.id).tonot benil expect(customerobject.defaultcard).tonot benil # etc. end ```

Customizing Webhooks

By default, StripeMock searches in your spec/fixtures/stripe_webhooks/ folder for your own, custom webhooks. If it finds nothing, it falls back to test events generated through stripe's webhooktester.

For example, you could create a file in spec/fixtures/stripe_webhooks/invoice.created.with-sub.json, copy/paste the default from the default invoice.created.json, and customize it to your needs.

Then you can use that webook directly in your specs:

ruby it "can use a custom webhook fixture" do event = StripeMock.mock_webhook_event('invoice.created.with-sub') # etc. end

You can alse override values on the fly:

ruby it "can override webhook values" do # NOTE: given hash values get merged directly into event.data.object event = StripeMock.mock_webhook_event('customer.created', { :id => 'cus_my_custom_value', :email => 'joe@example.com' }) # Alternatively: # event.data.object.id = 'cus_my_custom_value' # event.data.object.email = 'joe@example.com' expect(event.data.object.id).to eq('cus_my_custom_value') expect(event.data.object.email).to eq('joe@example.com') end

You can name events whatever you like in your spec/fixtures/stripe_webhooks/ folder. However, if you try to call a non-standard event that's doesn't exist in that folder, StripeMock will throw an error.

If you wish to use a different fixture path, you can set it yourself:

StripeMock.webhook_fixture_path = './spec/other/folder/'

Generating Card Tokens

Sometimes you need to check if your code reads a stripe card correctly. If so, you can specifically assign card data to a generated card token:

```ruby it "generates a stripe card token" do cardtoken = StripeMock.generatecardtoken(last4: "9191", expyear: 1984)

cus = Stripe::Customer.create(card: cardtoken) card = cus.cards.data.first expect(card.last4).to eq("9191") expect(card.expyear).to eq(1984) end ```

Debugging

To enable debug messages:

StripeMock.toggle_debug(true)

This will only last for the session; Once you call StripeMock.stop or StripeMock.stop_client, debug will be toggled off.

If you always want debug to be on (it's quite verbose), you should put this in a before block.

Miscellaneous Features

You may have noticed that all generated Stripe ids start with test_. If you want to remove this:

```ruby

Turns off test_ prefix

StripeMock.globalidprefix = false

Or you can set your own

StripeMock.globalidprefix = 'myapp' ```

TODO

  • Cover all stripe urls/methods
  • Throw useful errors that emulate Stripe's requirements
    • For example: "You must supply either a card or a customer id" for Stripe::Charge
  • Fingerprinting for other resources besides Cards

Developing stripe-ruby-mock

Please see this wiki page

Patches are welcome and greatly appreciated! If you're contributing to fix a problem, be sure to write tests that illustrate the problem being fixed. This will help ensure that the problem remains fixed in future updates.

Copyright

Copyright (c) 2013 Gilbert

See LICENSE.txt for details.

Owner

  • Name: Andrew Nesbitt
  • Login: andrew
  • Kind: user
  • Location: Bristol, UK
  • Company: @ecosyste-ms and @octobox

Working on mapping the world of open source software @ecosyste-ms and empowering developers with @octobox

GitHub Events

Total
Last Year

Committers

Last synced: 10 months ago

All Time
  • Total Commits: 404
  • Total Committers: 62
  • Avg Commits per committer: 6.516
  • Development Distribution Score (DDS): 0.438
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Gilbert g****a@g****m 227
Nicolás Hock Isaza n****i@g****m 21
Greg Yardley g****g@y****a 16
AlexMamonchik a****k@g****m 15
GeorgeErickson g****5@m****u 11
Stuart Olivera s****t@s****m 9
Edd Morgan e****m@m****m 7
Michael Raimondi z****o@p****m 6
theoretick l****s@h****g 5
RipTheJacker k****i@g****m 4
Andrew Thorp a****p@g****m 3
Gene Le g****l@g****m 3
Godfrey Chan g****c@g****m 3
Ivan Vanderbyl i****l@m****m 3
Zachary Salzbank z****h@k****e 3
ecl1pse e****n@g****m 3
Antonio Borrero Granell a****o@b****m 2
Benjamin Guez b****z@g****m 2
Bryan Goldstein b****o@g****m 2
Chris Shorrock c****k@g****m 2
Eric Bakan e****c@e****m 2
Eric Xu e****r@g****m 2
Jean-Philippe Doyle j****e@h****m 2
Jeremy Ward j****d@g****m 2
Jon Moter j****m@o****m 2
Michal Dulat m****l@d****l 2
Nathan Hawes n****h@h****k 2
Nikolai Berkoff a****v@g****m 2
Nikolai Berkoff n****f@b****m 2
Ryan McGeary r****n@m****g 2
and 32 more...

Issues and Pull Requests

Last synced: 10 months ago

All Time
  • Total issues: 0
  • Total pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Total issue authors: 0
  • Total pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
Pull Request Authors
Top Labels
Issue Labels
Pull Request Labels