Last active
March 11, 2019 10:19
-
-
Save rslhdyt/425747e1b5b55b01224e351121b08af3 to your computer and use it in GitHub Desktop.
Rspec Race Conditions
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
describe 'Race condition POST /api/v1/transaction/electricity', vcr: { cassette_name: 'race_condition_transaction_electricity' } do | |
it { expect(ActiveRecord::Base.connection.pool.size).to eq(5) } | |
context 'send requests simultaneously' do | |
let!(:user) { create(:user, limit_credit: 500_000, balance: 60_000) } | |
it 'should create one transaction' do | |
begin | |
concurrency_level = 4 | |
fail_occurred = false | |
wait_for_it = true | |
threads = Array.new(concurrency_level) do |_i| | |
Thread.new do | |
true while wait_for_it | |
begin | |
post '/api/v1/transaction/electricity', params: transaction_params, headers: transaction_headers | |
fail_occurred = (response.status == 422) | |
end | |
end | |
end | |
wait_for_it = false | |
threads.each(&:join) | |
user.reload | |
# dari 4 percobaan transaksi terdapat 3 transaksi gagal | |
expect(fail_occurred).to be(true) | |
expect(user.balance.to_i).to eq(8_500) | |
# transaksi yang tergenerate hanya 1 transaksi | |
expect(Transaction.all.count).to eq(1) | |
ensure | |
ActiveRecord::Base.connection_pool.disconnect! | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment