How to overwrite and reset constants within Cucumber features

Updated . Posted . Visible to the public. Deprecated.

Note: Prefer to not configure your app using global constants and use Rails.configuration instead (in application.rb). For Class Constants use the Rspec method stub_const.

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.

Ulrich Berkmüller
Last edit
Arne Hartherz
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Ulrich Berkmüller to makandra dev (2012-02-14 13:48)