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

How to stub class constants in RSpec

You can do this with vanilla RSpec now. This card needs to be rewritten or deleted.

Hint: There's another card with this helper for Cucumber features.


Sometimes you feel like you need to stub some CONSTANT you have defined in an other class. Since actually constants are called constants because they're constant, there's no way to easily stub a constant.

Here are three solutions for you.

Easiest solution

Rethink! Do you really need CONSTANT = %w[foo bar] to be constant? In many cases, setting it as a simple attribute will do.

Easy workaround

Define a method that returns the constant and stub that method:

Copy
class Earth TILT = 23.4 #degree def self.tilt TILT end end
Copy
Earth.should_receive(:tilt).and_return 10.5 # or Earth.stub :tilt => 10.5

Sometimes you can't add this method and must have that CONSTANT there. Master mode is for you.

Master mode (Rails 2)

Put the attached file into your spec directory, then merge these lines into your spec_helper.rb:

Copy
require 'spec/constants_helper' Spec::Runner.configure do |config| # ... config.include ConstantsHelper config.after(:each) do reset_all_constants end end

Now use it like this: overwrite_constant "CRAWL_SUBPAGES", false.\ Note: the constant must be given as String.

Master mode (Rails 3)

In Rails 3 applications you should prefer to set configuration options in Rails.configuration, which you can stub.

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Dominik Schöler
Last edit:
over 2 years ago
by Henning Koch
Attachments:
constants_helper.rb
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more