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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)