Testing money
The tests I want around any code that touches amounts, from integer halalas to refunds that must never add up to more than the payment.
I work on a payment gateway, so a lot of the code I review has a currency attached to it. Money code looks simple. It’s mostly adding, subtracting and multiplying by a percentage. That’s exactly why it’s dangerous: nobody expects arithmetic to be the bug.
These are the tests I want to see before money code ships. None of them are clever. They just cover the places where I’ve learned to expect problems.
Amounts are integers
The first test isn’t really a test. It’s a rule: amounts are stored and passed around as integers in the smallest unit of the currency. For Saudi riyals that’s halalas, so 10.50 SAR is 1050.
Floats can’t represent most decimal fractions exactly:
1
2
0.1 + 0.2
# => 0.30000000000000004
That’s harmless in a single calculation and a real problem across a million transactions, or in a reconciliation report that has to match a bank statement to the halala.
The trap is that “smallest unit” isn’t always a hundredth. The Kuwaiti dinar, Bahraini dinar and Omani rial have three decimal places. The Japanese yen has none. If your code ever divides by 100 to display an amount, there should be a test that runs it with a three-decimal currency.
1
2
3
4
it "formats three-decimal currencies" do
expect(Money.format(1_500, "KWD")).to eq("1.500 KWD")
expect(Money.format(1_500, "SAR")).to eq("15.00 SAR")
end
Rounding is a decision
The moment you multiply by a rate, you get fractions of a halala, and something has to decide where they go. A 2.75% fee on 19.99 SAR is 54.9725 halalas. That becomes 55, but only because somebody chose a rounding rule.
The rule should be written down, and the tests should sit right on the boundaries, where the rule actually shows up:
1
2
3
4
it "rounds half up at the boundary" do
expect(Fee.for(amount: 200, rate: BigDecimal("0.0025"))).to eq(1) # exactly 0.5
expect(Fee.for(amount: 199, rate: BigDecimal("0.0025"))).to eq(0) # 0.4975
end
Pick a rate and an amount that land exactly on .5, because that’s where half-up and banker’s rounding disagree. If nobody can say which one you want, that’s a conversation to have before it’s a bug.
Parts must add up to the whole
This is the test I’d keep if I could only keep one. Whenever you split an amount, the pieces have to sum back to the original.
Split 100 halalas three ways and each share is 33.33. Round each one and you get 99. One halala has disappeared, and it will turn up later as a reconciliation difference that someone spends an afternoon on. The fix is to hand the remainder out deliberately, and the test is a plain loop over a lot of awkward inputs:
1
2
3
4
5
6
7
8
9
10
it "never loses or invents a halala when splitting" do
1_000.times do
total = rand(1..10_000_000)
parts = rand(1..7)
shares = Allocation.split(total, parts)
expect(shares.sum).to eq(total)
expect(shares.max - shares.min).to be <= 1
end
end
The same idea applies to refunds. However many partial refunds come in, in whatever order, they must never add up to more than what was captured.
1
2
3
4
5
6
7
it "rejects a refund that would exceed the captured amount" do
payment = create(:payment, :captured, amount: 10_000)
payment.refund!(6_000)
expect { payment.refund!(4_001) }.to raise_error(Payment::RefundExceedsCapture)
expect(payment.reload.refunded_amount).to eq(6_000)
end
Note the second expectation. A refund that fails halfway can be worse than one that’s rejected cleanly.
The same request twice
Networks retry. Mobile apps retry. People double-tap. A payment endpoint that charges twice when it receives the same request twice will eventually charge someone twice.
The usual defence is an idempotency key: the client sends a unique key with the request, and the server returns the original result if it has seen that key before. It deserves its own tests, including the uncomfortable one where both requests arrive at the same time:
1
2
3
4
5
6
it "creates one charge for two identical requests" do
2.times { post "/payments", params: params, headers: { "Idempotency-Key" => "abc-123" } }
expect(Payment.count).to eq(1)
expect(response.parsed_body["id"]).to eq(Payment.last.id)
end
The concurrent version is harder to write and more important. If the check is “look it up, and if it isn’t there, insert it”, two requests can both look, both find nothing, and both insert. A unique index on the key turns that race into an error you can handle.
States only move forward
A payment goes through a handful of states: initiated, authorized, captured, refunded, failed. The bugs that worry me most here come from a transition that should be impossible but isn’t, like capturing a failed payment or refunding one that was never captured.
I like to test the forbidden transitions explicitly, every pair, rather than only the happy path. It’s a small table:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
FORBIDDEN = {
failed: %i[authorized captured refunded],
refunded: %i[authorized captured],
initiated: %i[refunded],
}
FORBIDDEN.each do |from, targets|
targets.each do |to|
it "can't go from #{from} to #{to}" do
payment = create(:payment, status: from)
expect { payment.transition_to!(to) }.to raise_error(Payment::InvalidTransition)
end
end
end
When someone adds a new state later, this table is where they find out what they’ve forgotten.
Midnight is in Riyadh
Daily reports, settlement batches and “today’s volume” all depend on where midnight is. Riyadh is UTC+3 all year, with no daylight saving. A payment made at 1:00 in the morning in Riyadh happened at 22:00 UTC the day before. If your database stores UTC and your report groups by date, one of those two days is going to be wrong unless you’ve tested it.
1
2
3
4
5
6
7
8
it "counts a 1am Riyadh payment in that Riyadh day" do
travel_to Time.find_zone("Asia/Riyadh").local(2026, 3, 2, 1, 0) do
create(:payment, :captured, amount: 5_000)
end
expect(DailyReport.for(Date.new(2026, 3, 2)).volume).to eq(5_000)
expect(DailyReport.for(Date.new(2026, 3, 1)).volume).to eq(0)
end
None of this is exciting
That’s the point. Money code doesn’t need clever tests. It needs boring ones written by someone who has thought about the edges: a currency with three decimals, a rate that lands on exactly half a halala, two requests in the same millisecond, a payment at one in the morning.
Write those, run them on every change, and most of the interesting money bugs never happen.