rspec-rails-controller

Lightweight controller macros for Rails 3 and RSpec.

Usage

The following controller spec:

get! :show, :id => 1 do
  its(:response) { should be_success }
  its(:response) { should render_template(:show) }
end

...gets translated into the following stock rspec/rails spec:

describe 'GET #show' do
  context 'action' do
    before(:each) { get :show, :id => 1 }
    its(:response) { should be_success }
    its(:response) { should render_template(:show) }
  end
end

The bang implies the before(:each) statement. If you need more control, use the non-bang version and call action! or use an action!.

post :create, :user => { :name => 'bob' } do
  it { lambda { action! }.should change(User, :count).by(1) }
  action! do
    its(:response) { should be_redirect }
    its(:response) { should redirect_to(user_path(assigns(:user))) }
  end
end

Params can be a hash or a block. Blocks are evaluated when the action is fired. Params can be specified within nested describe/context blocks.

before(:all) { @user = User.create(:name => 'bob') }
put :update do
  context 'with valid params' do
    params { { :id => @user.id, :user => { :name => 'fred' } } }
    action! do
      its(:response) { should be_redirect }
      its(:response) { should redirect_to(user_path(assigns(:user))) }
    end
  end
  context 'with unknown user' do
    params :id => -1
    it { lambda { action! }.should raise_error(ActiveRecord::RecordNotFound) }
  end
  context 'with invalid params' do
    params { { :id => @user.id, :user => { :name => '' } } }
    action! do
      its(:response) { should be_success }
      its(:response) { should render_template(:edit) }
    end
  end
end

Installation

Note, this gem depends on rspec/rails. Make sure you follow the installation instructions before you install this gem.

Add rspec-rails-controller to the :test group in the Gemfile:

group :test do
  gem 'rspec-rails-controller'
end

Run the bundle installer:

bundle install

In your spec/spec_helper.rb, add the require statement below rspec/rails:

require 'rspec/rails'
require 'rspec/rails/controller'

In your spec/spec_helper.rb, add the include statement in your RSpec.configure block:

RSpec.configure do |config|

  # ...

  config.include RSpec::Rails::Controller::Macros, :type => :controller

end

Similar gems