Satya's blog - Stubbing the Rails environment for rspec

Jan 01 2012 08:28 Stubbing the Rails environment for rspec

From http://blog.thefrontiergroup.com.au/2011/06/stubbing-out-rails-env/

To stub the rails environment for rspec-based testing, you can add this function to spec_helper.rb:

def stub_env(new_env, &block)
    original_env = Rails.env
    Rails.instance_variable_set("@_env", ActiveSupport::StringInquirer.new(new_env))
    block.call
ensure
    Rails.instance_variable_set("@_env", ActiveSupport::StringInquirer.new(original_env))
end

And use it like this:

it "should have the correct default options" do
  stub_env('development') {
    # Rails.env.development? is now true
    # Do some thing here
  }
end

So stub_env gets called with what the environment should be. It saves the original environment and restores it later in the ensure block (to avoid test pollution -- other tests should not see the fake environment). It sets the requested environment and calls the block that was given to it.

The key here is that Rails.env accesses an instance variable on the Rails object and that instance variable is @_env.

ActiveSupport.StringInquirer is what that instance variable is supposed to contain. It's what allows us to do Rails.env.development? instead of Rails.env == 'development'. A ridiculous thing to do, in my opinion.

Tag: rails howto