Last active
October 10, 2023 05:03
-
-
Save goromlagche/835bd371d5e4825580e8c9e4430c7ea2 to your computer and use it in GitHub Desktop.
A sample rspec spec to test concurrent api calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you @goromlagche 🙇♀️ I didn't used the config though but I killed the threads after the spec was done