Here's a quick and dirty way to mock class constants in unit tests without using any gems.
Given this class:
module Query
class Paginator
PAGE_SIZE = 1000
def paginate(page:)
offset = if page > 1
per_page * (page.to_i - 1)
else
0
end
Person.order(:created_at)
.offset(offset)
.limit(PAGE_SIZE)
end
end
end
Given PAGE_SIZE is set to 1000 records, I think it's a bit of a lift to run a test with that much records so why not set the constant with a lower value in our tests?
module Query
class PaginatorTest < ActiveSupport::TestCase
setup do
# We change the constant value
Query::Paginator.send(:const_set, 'PAGE_SIZE', 1)
end
teardown do
# We restore the original value to avoid issues with other tests
Query::Paginator.send(:remove_const, "PAGE_SIZE")
end
...
end
end
You can set and unset the constant value in the test case body as well.
Top comments (0)