InjectableRailsEnv

Allows injecting the Rails env into a class for testing purpose.

It is not easy to simulate a special Rails environment like production or development during tests.

First we cannot mock the Rails environment methods like production? as follows:

Rails.env.should_receive(:production?).and_return(true)

Cause the method does not exists and the return value is delivered through method_missing internally.

Even if we could mock the method other code on the way from the specs to the class under test may call Rails.env.production? and our mocking would cause side effects here.

So we have to find another way to simulate the environment and this gem may help.

Installation

Via Bundler:

# path/to/railsapp/Gemfile
gem 'injectable_rails_env'

$ bundle install

Usage

Include the module into your class under test and replace all occurrences of Rails.env.production? with rails_env_production?.

Example:

# app/controllers/jobs_controller.rb
class JobsController < ApplicationController
  include InjectableRailsEnv

  before_filter :authenticate

  def index
    ...
  end

  private

  def authenticate
    return unless rails_env_production? # intead of Rails.env.production?
    redirect_to login_url unless logged_in?
  end

end

Now you can simulate the Rails env via rails_env=:

# spec/controllers/jobs_controller.rb
describe JobsController do

  context "Rails env is production" do

    it "requests authentication" do
      @controller.rails_env = "production"

      get :index
      response.should be_redirect
      response.should redirect_to 
    end
  end

  context "Rails env is non production" do

    it "allows access without authentication" do
      @controller.rails_env = "non-production"

      get :index
      response.should be_success
      response.should render_template "index"
    end
  end
end

Note that this won’t work on class level. Consider the following example:

# app/controllers/jobs_controller.rb
class JobsController < ApplicationController
  include InjectableRailsEnv

  before_filter(:authenticate) if rails_env_production?
  ...
end

When running the specs the JobsController code is executed before the spec starts and rails_env has not been set. Therefore rails_env_production? will always return the value of Rails.env.production?.

You have to change your code from using rails_env_production? on the class level to using it on the instance level (like in the example above in authenticate).

Supported Environments

Supported environments are test, development, production, stating, integration and ci. So for each there is a method rails_env_ENV?.

Contact

For comments and question feel free to contact me: [email protected]

If you are using the plugin, consider recommending me at workingwithrails.com: workingwithrails.com/person/6131-thomas-baustert

Copyright © 2012 [Thomas Baustert], released under the MIT license