ruby-on-railsrubyrspectimecop

Ruby constant date variable with respect to timecop in rspec


Hi I have a Ruby class with some constant variables using Date:

START_DATE = Date.current.at_beginning_of_month.in_time_zone + 2.days

LAST_DATE = Date.current.at_beginning_of_month.in_time_zone + 10.days

and I have some methods which uses this date inside like below:

Date.current.in_time_zone.between?(START_DATE, LAST_DATE)

in my rspec file I'm using Timecop.freeze and it's breaking my tests.

Is there a workaround to use the same variable for most of my methods? or am I using this incorrectly?

I would appreciate any help!


Solution

  • I actually got this answer from the Ruby slack community I got a suggestion to make it a method.

    so something like:

    def start_date
      Date.current.at_beginning_of_month.in_time_zone + 2.days
    end
    

    I also just learned what @spickermann meant with why I shouldn't use constant variable because it will stay constant from the start of the server it will have the initial value. and technically, it's not a constant. :sweatsmile: