Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 782
nrmb Avatar asked Dec 07 '25 05:12

nrmb


2 Answers

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:

like image 167
nrmb Avatar answered Dec 08 '25 19:12

nrmb


Whether or not you use Timecop for other interactions in your tests, you may also want to consider stubbing the constants themselves. Once you've tested the logic involved with setting the constants, consider using stub_const to ensure that the constants are set to the values you want in your test suite. For example, you might include a block in your test suite that looks something like this:

before :each do
  stub_const("MyClass::START_DATE", <start_time>)
  stub_const("MyClass::END_DATE", <end_time>)
end

Updated:

Comment below says this doesn't work, which is odd... definitely works for me. Just tested this like this:

class User
  MY_CONST = "foo"

  def my_method
    MY_CONST
  end
end

and then in rspec:

describe User do
  it "works unstubbed" do
    expect(User.new.my_const).to eq("foo")
  end
  it "works stubbed" do
    stub_const("User::MY_CONST", "bar")
    expect(User.new.my_const).to eq("bar")
  end
end
like image 33
Adam Berman Avatar answered Dec 08 '25 17:12

Adam Berman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!