Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created January 22, 2020 03:50
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 inopinatus/8d2ba72a7aa825f95b263cfa2c9f6910 to your computer and use it in GitHub Desktop.
Save inopinatus/8d2ba72a7aa825f95b263cfa2c9f6910 to your computer and use it in GitHub Desktop.
ActiveSupport's Date#all_* ranges inadvertently exclude times that should match.
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
gem "sqlite3"
end
require "active_record"
require "logger"
require "minitest/autorun"
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
t.string :name
t.datetime :born_at
end
end
class User < ActiveRecord::Base
scope :same_birth_year, ->(date) { where born_at: date.all_year }
def same_birth_year?(date)
date.all_year.cover?(born_at)
end
end
class RangeTest < Minitest::Test
def setup
User.delete_all
@users = User.create! [
{ name: "User1", born_at: '2019-12-25 16:32 UTC' },
{ name: "User2", born_at: '2019-12-31 23:01 UTC' },
{ name: "User3", born_at: '2020-01-01 00:00 UTC' }
]
@dob = Date.parse('2019-06-01')
end
def test_same_birth_year_count
assert_equal 2, User.same_birth_year(@dob).count
end
def test_birth_year_coverage
assert_equal [true, true, false], @users.map { |user| user.same_birth_year?(@dob) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment