# Terminal
rails test
# test/controllers/purchases_controller_test.rb
require 'test_helper'
class PurchasesControllerTest < ActionDispatch::IntegrationTest
setup do
sign_in users(:user_one)
@product = products(:tenvbucks)
end
test "should create purchase" do
post purchases_url, params: { product_id: @product.id, format: :js }
assert_response :success
end
end
# test/fixtures/products.yml
tenvbucks:
name: 10 vbucks
price: 9.99
quantity: 10
# test/fixtures/users.yml
user_one:
first_name: John
last_name: Doe
email: [email protected]
encrypted_password: <%= User.new.send(:password_digest, '123456') %>
# test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
include Devise::Test::IntegrationHelpers
include Warden::Test::Helpers
end
# test/models/payment_received_test.rb
require 'test_helper'
class PaymentReceivedTest < ActiveSupport::TestCase
setup do
@user = users(:user_one)
json = {
data: {
object: {
id: 'test',
amount_subtotal: 999,
amount_total: 999,
client_reference_id: @user.id,
customer: 'test_stripe_id'
}
}
}.to_json
@payment = JSON.parse(json, object_class: OpenStruct)
end
test "should credit user vbucks" do
assert_equal @user.vbuck.to_i, 0
payment_received = PaymentReceivedMock.call(@payment)
@user.reload
assert_equal @user.stripe_id, 'test_stripe_id'
assert payment_received
assert_equal @user.vbuck, 20
end
end
class PaymentReceivedMock < PaymentReceived
private
def line_items
[
OpenStruct.new(description: '10 vbucks', quantity: 1),
OpenStruct.new(description: '10 vbucks', quantity: 1)
]
end
end
# app/models/payment_received.rb
...
def call
return false unless user
user.update(stripe_id: object.customer) unless user.stripe_id
complete_purchase
true
end
...