nrmb
nrmb

Reputation: 490

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!

Upvotes: 3

Views: 949

Answers (2)

Adam Berman
Adam Berman

Reputation: 794

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

Upvotes: 1

nrmb
nrmb

Reputation: 490

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:

Upvotes: 2

Related Questions