Skip to content

Instantly share code, notes, and snippets.

@serradura
Last active February 8, 2022 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serradura/9a57a51a9995503bc58ec405b3042bb0 to your computer and use it in GitHub Desktop.
Save serradura/9a57a51a9995503bc58ec405b3042bb0 to your computer and use it in GitHub Desktop.
Using dependency injection to improve testability
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rspec', '~> 3.10'
gem 'activesupport', require: 'active_support/all'
end
module Calc
def self.get_tax(amount, time: Time.now)
tax = 7
tax = tax + 10 if amount.to_f >= 1000
if time.on_weekday?
tax = 5 if time.hour >= 9 && time.hour <= 18
end
tax
end
end
require 'rspec/autorun'
RSpec.describe Calc do
describe '.get_tax' do
context 'when the amount is greater than or equal to 1000' do
context 'and now is a weekday but is not a business hour' do
it 'returns 17' do
time = double(on_weekday?: true, hour: 8)
tax = Calc.get_tax(1001, time: time)
expect(tax).to be == 17
end
end
end
end
end
@serradura
Copy link
Author

Refactoring Calc.get_tax.

module Calc
  def self.get_tax(amount, time: Time.now)
    tax = amount.to_i >= 1000 ? 17 : 7

    return tax unless time.on_weekday?

    time.hour >= 9 && time.hour <= 18 ? 5 : tax
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment