Module: Amount::RSpec::Matchers
- Defined in:
- lib/amount/rspec/matchers.rb
Overview
Internal matcher helpers for the opt-in RSpec integration.
All bare ‘RSpec` references inside this module are fully qualified to `::RSpec` to dodge the constant-lookup ambiguity introduced by living under `Amount::RSpec`.
Class Method Summary collapse
- .define_amount_equality_matcher(name, &expected_builder) ⇒ Object
- .define_amount_predicate_matcher(name, description, &predicate) ⇒ Object
- .define_amount_type_matcher ⇒ Object
- .define_approximate_amount_matcher ⇒ Object
Class Method Details
.define_amount_equality_matcher(name, &expected_builder) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/amount/rspec/matchers.rb', line 13 def define_amount_equality_matcher(name, &expected_builder) ::RSpec::Matchers.define name do |*arguments| match do |actual| @expected = instance_exec(*arguments, &expected_builder) actual.is_a?(Amount) && actual == @expected end do |actual| return "expected #{actual.inspect} to be an Amount equal to #{@expected.inspect}" unless actual.is_a?(Amount) "expected #{actual.inspect} to equal amount #{@expected.inspect}" end end end |
.define_amount_predicate_matcher(name, description, &predicate) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/amount/rspec/matchers.rb', line 28 def define_amount_predicate_matcher(name, description, &predicate) ::RSpec::Matchers.define name do match do |actual| actual.is_a?(Amount) && instance_exec(actual, &predicate) end do |actual| "expected #{actual.inspect} to be #{description}" end end end |
.define_amount_type_matcher ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/amount/rspec/matchers.rb', line 40 def define_amount_type_matcher ::RSpec::Matchers.define :be_amount_of do |expected_symbol| match do |actual| @expected_symbol = expected_symbol.to_sym actual.is_a?(Amount) && actual.symbol == @expected_symbol end do |actual| "expected #{actual.inspect} to be an Amount of #{@expected_symbol}" end end end |
.define_approximate_amount_matcher ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/amount/rspec/matchers.rb', line 53 def define_approximate_amount_matcher ::RSpec::Matchers.define :be_approximately_amount do |*expected_arguments, within:| match do |actual| @expected = Amount::RSpec::Support.coerce_amount_arguments(expected_arguments) @within = Amount::RSpec::Support.coerce_delta(@expected, within) actual.is_a?(Amount) && actual.same_type?(@expected) && @within.same_type?(@expected) && (actual - @expected).abs.atomic <= @within.atomic end do |actual| return "expected #{actual.inspect} to be an Amount within #{@within.inspect} of #{@expected.inspect}" unless actual.is_a?(Amount) "expected #{actual.inspect} to be within #{@within.inspect} of #{@expected.inspect}" end end end |