require 'rspec' require 'time' require 'active_support/time' class Foo def float_range_example 33 * 5 * Math::PI end def time_range Time.now end def hash_with_range_value { id: 1, created_at: Time.now, city: "Banska Bystrica" } end def array_with_range_values [Time.now, Time.now.midnight, Time.now.midday, 3.days.ago] end def array_with_hash_with_range_value [ { id: 12, created_at: Time.now }, { id: 33, created_at: Time.now.midnight } ] end end RSpec.describe(Foo) do subject { described_class.new } describe '#float_range_example' do it do # if the value is from e.g.DB than this may not be true # # expect(subject.float_range_example).to eq(518.3627878423158) # # therefore we must define range of value where that float number # value is acceptable expect(subject.float_range_example).to be_within(0.01).of(518.3627878423158) end end describe '#time_range' do context 'in pure Ruby' do it do expect(subject.time_range).to be_within(1).of(Time.now) end end context 'in Rails' do it do expect(subject.time_range).to be_within(1.second).of(Time.now) end end end describe '#hash_with_range_value' do it do expect(subject.hash_with_range_value).to match({ id: 1, created_at: be_within(1.second).of(Time.now), city: /[bB]an/ }) end end describe '#array_with_range_values' do it do expect(subject.array_with_range_values).to match_array([ be_within(2.seconds).of(Time.now), be_within(2.seconds).of(Time.now.midnight), be_within(2.seconds).of(Time.now.midday), be_within(2.seconds).of(Time.now - 3.days), ]) end end describe '#array_with_hash_with_range_value' do it do expect(subject.array_with_hash_with_range_value).to match_array([ { id: 12, created_at: be_within(2.seconds).of(Time.now) }, { id: 33, created_at: be_within(2.seconds).of(Time.now.midnight) } ]) end end end # Resources # # * RSpec version 3.4 # * Ruby 2.3.0 # * https://www.relishapp.com/rspec/rspec-expectations/v/2-8/docs/built-in-matchers/be-within-matcher