The Spaghetti Refactory Established 2015

Rspec tricks for DRY mocked specs

These “tricks” are straight from the docs. One will help DRY up your specs, the other will help you mock your controller for controller tests.

Shared Contexts

Shared context allows for extracting certain setup steps and sharing them across several different sets of tests.

First, define your shared context:

RSpec.shared_context "user setup" do
let(:user) { User.new(name: 'Chuck Norris') }
before { allow(user).to receive(:some_method) }
end

Then, include it in your spec files:

describe UsersController do
include_context 'user setup'

# Tests go here...
end

Anonymous Controllers

Anonymous controllers are a way to specify certain behavior for the controller you are trying to test, or more likely for a parent controller. The thing I found it most useful for, and not coincidentally the thing that the docs says it is useful for, is testing global error handling.

describe UsersController do
controller do
def index
raise AccessDenied
end
end

subject { get :index }

describe "handling AccessDenied exceptions" do
it "redirects to the /401.html page" do
expect(subject).to redirect_to("/401.html")
end
end
end

Tags