Faster Tests - How to Decouple Rails 4 Controllers?

149 views Asked by At

Why this Matters

Testing Ruby methods isolated from the Rails framework == dramatically shorter testing times.

The Problem

How do I correctly decouple the Rails 4 controllers?

Where things are now

Presently, this is my rspec error:

NameError:
  undefined local variable or method `response'

This is how I decouple and mock the ActionController in my controller_spec test file. It is a hodgpodge of my research on what works for Rails 3 and addressing the error messages that arose in my experiments. I don't believe this works because I am either not setting some attribute that ActionController needs or I am inadvertently turning something off. It seems Rails 4 added some complexity to the controller.

APP_ROOT = File.expand_path(File.join(File.dirname__FILE__), "..", "..", ".."))
$: << File.join(APP_ROOT, "app/controllers")

module ActionController
  class Base
    class << self
      attr_reader :before_filters
      attr_reader :skipped_before_filters
    end

    def self.before_filter(*args)
      @before_filters ||= []
      @before_filters << args
    end

    def self.skip_before_filter(*args)
      @skipped_before_filters ||= []
      @skipped_before_filters << args
    end

    def self.allow_forgery_protection=(val); end
    def self.allow_forgery_protection; end

    def self.protect_from_forgery(*args); end   
    def self.after_filter(*args); end

    def request=(val); end
    def request; end
    def params=(val); end
    def redirect_to(*args); end
    def render_template(*args); end
    def _compute_redirect_to_location(*args); end

  end
end

These are my spec tests which were passing before I began this experiment:

describe "GET #home" do
  subject(:action) {get :home}

  it "is successful" do
    expect(action).to be_success
  end
  it "returns HTTP 200 status" do
    expect(action.status).to eq(200)
  end
  it "renders the home template" do 
    expect(action).to render_template("home")
  end

end

My controller action does nothing but render the home view and works as expected:

def home
end

Thank you.

Links about Decoupling in Rails 3:

  1. Running Rails Rspec Tests without Rails
  2. Rails 3, The Great Decoupling
0

There are 0 answers