Skip to content

Instantly share code, notes, and snippets.

@rslhdyt
Last active March 11, 2019 10:19
Show Gist options
  • Save rslhdyt/425747e1b5b55b01224e351121b08af3 to your computer and use it in GitHub Desktop.
Save rslhdyt/425747e1b5b55b01224e351121b08af3 to your computer and use it in GitHub Desktop.
Rspec Race Conditions
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