Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Several examples how to use Ruby RSpec 3 `be_within` matcher for delta compare
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
@equivalent

This comment has been minimized.

Copy link
Owner Author

equivalent commented Jun 29, 2016

Full article can be found here => http://www.eq8.eu/blogs/27-rspec-be_within-matcher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.