Read more

How to stub class constants in RSpec

Dominik Schöler
July 30, 2011Software engineer at makandra GmbH

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.


Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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:

class Earth
  TILT = 23.4 #degree

  def self.tilt
    TILT
  end
end

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

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.

Posted by Dominik Schöler to makandra dev (2011-07-30 17:00)