Posted almost 7 years ago. Visible to the public. Repeats.

How to overwrite and reset constants within Cucumber features

Note: Prefer to not configure your app using global constants. Prefer to set keys in Rails.configuration instead (in application.rb).

In order to save the original value of a constant, set the new value and restore the old value after a scenario was completed, you can use the following helper. It takes care of saving the old constant value, setting the new one without throwing warnings and resets the value with an After hook.

This module also enables you to introduce new global constants.
Since these newly defined constants do not have any value to be reset to,
they simply are deleted (remove_const) once the respective Cucumber step finishes.

You can copy the file attached and save it to your features/support/ directory. After that simply use the helper method within your steps as shown in the following example:

Given /^the pagination limits users to "(\d+)" entries$/ do |max_users_per_page| overwrite_constant "MAX_USERS_PER_PAGE", max_users_per_page.to_i end

By default, overwrite_constant overwrites constants defined on Object. The third parameter can be used to pass the object which defines the constants you like to overwrite:

overwrite_constant "MAX_USERS_PER_PAGE", 10, MyCustomObject

There's a card with the constants helper for Rspec.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Ulrich Berkmueller
Last edit:
almost 4 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Ulrich Berkmueller to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more