Skip to content

Instantly share code, notes, and snippets.

@goromlagche
Last active October 10, 2023 05:03
Show Gist options
  • Save goromlagche/835bd371d5e4825580e8c9e4430c7ea2 to your computer and use it in GitHub Desktop.
Save goromlagche/835bd371d5e4825580e8c9e4430c7ea2 to your computer and use it in GitHub Desktop.
A sample rspec spec to test concurrent api calls
require 'rails_helper'
describe Api::V1::CheckoutsController, type: :request do
let(:user) do
FactoryGirl.create(:user, current_balance: 100_000)
end
describe 'check concurrency' do
it 'send multiple same requests', truncation_only: true do
FactoryGirl.create(:item,
user: user,
amount: 10_000, item_uuid: '1234')
FactoryGirl.create(:item,
user: user,
amount: 30_000, item_uuid: '5678')
FactoryGirl.create(:item,
user: user,
amount: 20_000, item_uuid: 'abcd')
headers = { 'ACCEPT' => 'application/json',
'HTTP_AUTHORIZATION' => http_basic_auth(user.api_key,
'') }
threads = []
threads << Thread.new do
post '/api/v1/user/checkout',
headers: headers,
params: { item_uuids: %w[1234 5678] }
end
threads << Thread.new do
post '/api/v1/user/checkout',
headers: headers,
params: { item_uuids: %w[1234 5678] }
end
threads << Thread.new do
post '/api/v1/user/checkout',
headers: headers,
params: { item_uuids: %w[1234 5678] }
end
threads << Thread.new do
post '/api/v1/user/checkout',
headers: headers,
params: { item_uuids: %w[1234 abcd] }
end
threads.each(&:join)
user.reload
expect(user.current_balance).to be >= 0
expect(user.current_balance).to be 40_000
expect(TransactionHistory.count).to eq 3
end
end
end
RSpec.configure do |config|
config.use_transactional_fixtures = false
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before do |example|
if example.metadata[:truncation_only]
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.start
else
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.start
end
end
config.after do
DatabaseCleaner.clean
end
end
@iffyuva
Copy link

iffyuva commented Mar 7, 2018

Typo in truncation spelling :D

@goromlagche
Copy link
Author

fixed, thanks 😄

@maruarcus
Copy link

Thank you @goromlagche 🙇‍♀️ I didn't used the config though but I killed the threads after the spec was done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment