How to override Constant referenced from inside validates for RSpec

Viewed 2731

My model has custom validates like this.

class User
  # skip before

  MAX_FILE_SIZE = 10.megabytes.to_i
  validates :file, size: { max: MAX_FILE_SIZE }

  # skip after
end

And, I'd like to test about MAX_FILE_SIZE by override MAX_FILE_SIZE in spec. So, I wrote like this.

context "MAX_FILE_SIZE is default" do
  it do
    # test something
  end
end
context "MAX_FILE_SIZE is 1byte" do
  before do
    stub_const "User::MAX_FILE_SIZE", 1.bytes.to_i
  end
  it do
    # test something
  end
end

First test was passed. However, second test was failed due to MAX_FILE_SIZE wasn't changed.

Could you tell me why? And how to solve this situation.

3 Answers

You could make a use of lambdas and define the validation like this:

class User
  # skip before

  MAX_FILE_SIZE = 10.megabytes.to_i
  validates :file, size: { max: -> { MAX_FILE_SIZE } }

  # skip after
end

This way, it should be "reevaluated" properly after you stub the const.

Related