Read more

How to overwrite and reset constants within Cucumber features

Ulrich Berkmueller
February 14, 2012Software engineer

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Ulrich Berkmueller to makandra dev (2012-02-14 14:48)