Skip to content

Instantly share code, notes, and snippets.

@joshk
Created January 31, 2011 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshk/804718 to your computer and use it in GitHub Desktop.
Save joshk/804718 to your computer and use it in GitHub Desktop.
require 'bigdecimal'
class Payment
FEE_PERCENTAGE = BigDecimal.new('2.9')
FEE_SET_AMOUNT = BigDecimal.new('0.15')
attr_reader :amount
def initialize(amount)
@amount = BigDecimal.new(amount.to_s)
end
def fee_amount
(rounded_fee_percentage + FEE_SET_AMOUNT).to_f
end
private
def rounded_fee_percentage
fee_percentage = FEE_PERCENTAGE / 100
(@amount * fee_percentage).round(2)
end
end
RSpec::Matchers.define :have_a_fee_amount_of do |amount|
match do |payment|
payment.fee_amount == amount
end
failure_message_for_should do |payment|
"expected a payment of $#{payment.amount.to_f} to have a fee amount of $#{amount}"
end
failure_message_for_should_not do |actual|
"expected a payment of $#{payment.amount.to_f} to not have a fee amount of $#{amount}"
end
description do
"have a fee_amount of 2.9% + $0.15 ($#{amount})"
end
end
module PaymentExampleHelpers
def when_amount_is(amount, &block)
context "with an amount of $#{amount}" do
subject { Payment.new(amount) }
instance_eval(&block)
end
end
end
RSpec.configure do |config|
config.extend(PaymentExampleHelpers)
end
# although the combination of when_amount_is and have_a_fee_amount_of matcher
# increases the test size by a fair few lines, the idea was to remove duplication
# within the test descriptions and code. Also, this spec layout is more flexible
# to adding further tests within each when_amount_is block.
#
# as a side note, `rspec -f squareup_spec.rb` produces nice test documentation
#
describe Payment do
when_amount_is(10.00) do
it { should have_a_fee_amount_of(0.44) }
end
when_amount_is(42.00) do
it { should have_a_fee_amount_of(1.37) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment