简体   繁体   中英

How can I test my API created stripe customer properly?

I want to test the API request that creates Stripe customers.

Controller

def create
  user = User.create(create_params)
  stripe_customer = Stripe::Customer.create({
    email: create_params[:email],
    name: [create_params[:first_name], create_params[:last_name]].join(' ')
  })
  user.update(stripe_customer_id: stripe_customer.id)

  render(json: { user: user }, status: :ok)
end

private

def create_params
  params.permit(
    :email,
    :first_name,
    :last_name
  )
end

I saw there is stripe-ruby-mock gem but I am not sure how I can use it?

First of all, you should be able to trust that Stipe's gem will do the right thing when you call it. So, there's no need to test that their create method returns the correct thing. So, all you need to test is that you are calling their API correctly. All you need to do this is an RSpec mock.

Since your code is in a controller, you'll either need to use a controller spec, or you'll need to refactor your code into another class. My preference is the refactor. So, that's what I'll show here.

Controller

Refactored to move business logic into a command class.

def create
  user = CreateUser.new(create_params).perform

  render(json: { user: user }, status: :ok)
end

CreateUser command class

Refactored a bit to only make one call to the database.

class CreateUser
  attr_reader :params

  def initialize(params)
    @params = params
  end

  def perform
    stripe_customer = Stripe::Customer.create({
      email: params[:email], 
      name: [params[:first_name], params[:last_name]].join(' ')
    })

    User.create(params.merge(stripe_customer_id: stripe_customer.id))
  end
end

Spec file for CreateUser command class

describe CreateUser do
  subject(:create_user) { described_class.new(params)

  let(:params) do
    email: 'some@email.address', 
    first_name: 'first', 
    last_name: 'last'
  end

  describe 'perform' do 
    let(:stripe_customer_id) { 123 }

    before do
      allow(Stripe::Customer).to receive(:create).and_return(stripe_customer_id)
      allow(User).to receive(:create)
    end

    it 'creates a Stripe customer' do
      create_user.perform

      expect(Stripe::Customer).to have_received(:create).with(
        email: 'some@email.address', 
        name: 'first last'
      )
    end

    it 'creates a user with a stripe customer id' do
      create_user.perform

      expect(User).to have_received(:create).with(
        email: 'some@email.address',
        first_name: 'first', 
        last_name: 'last', 
        stripe_customer_id: 123
      )
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM