ruby-on-railsrubyminitest

Ruby tally method: evaluating a hash with a key that is a date


In testing a rails method with Minitest, the following statement

Available.all.reload.pluck(:date).tally

returns the following hash

{Sat, 08 Jun 2024=>2, Tue, 25 Jun 2024=>12, Sun, 07 Jul 2024=>11}

The assertion that is being attempted is, after a transformation of data, to validate that the value for date key 2024-07-07 == 11.
The following, under the assumption that hash keys are instances of Time, returns false;
there is a date typing issue either in the statement or in the transformation of it to the console.

new_date = DateTime.new(2024,7,8,0,0,0).to_time
assert Available.all.reload.pluck(:date).tally.include?({new_date=>11})

How should this be written?


Solution

  • ...under the assumption that hash keys are instances of Time

    Based on the post those are not instances of Time which would be represented via inspect as "%Y-%m-%d %H:%M:%S.%6N %z", instead these appear to be Date objects.

    First thing I would recommend is that

    Available.all.reload.pluck(:date).tally
    

    Is equivalent to

    Available.group(:date).count
    

    This offloads the counting to the database and avoids the creation of an intermediate disposed Array

    Secondly you can create a Date object using Date.new(2024,7,8).

    Since we are using a Hash we can simply lookup the key and compare the value like so

    Available.group(:date).count[Date.new(2024,7,8)] == 11
    

    That being said if the target is always a single Date and the Hash is not necessary then something like this might be more efficient:

    Available.where(date: Date.new(2024,7,8)).count == 11