Posted over 7 years ago. Visible to the public. Deprecated.

How to overwrite and reset constants within Cucumber features

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:

Copy
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:

Copy
overwrite_constant "MAX_USERS_PER_PAGE", 10, MyCustomObject

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

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Ulrich Berkmueller
Last edit:
7 months ago
by Emanuel De
Attachments:
overwrite_constant.rb
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