user341493
user341493

Reputation: 414

rspec controller test instance variable calls method

I'm trying to write a test for an ActiveAdmin controller that I inherited and I'm having trouble checking that an instance variable is calling a method. The behavior that I want is a side effect of calling the method so I would like to ensure that it's called.

Here's the controller:

ActiveAdmin.register User do
  controller do
    before_filter :get_user

    def get_user
      @user = User.find_by_login(params[:id])
      if !@user
        flash[:notice] = "No user found with that login"
        return false
      end
    end

  end
  member_action :tos_ban, :method => :post do
    @user.ban!(current_user, "admin ban", 1)
    flash[:notice] = "#{@user.display_name} successfully TOS Banned"
    redirect_back
  end
end

And, my spec:

require 'spec_helper'

describe ActiveAdmin::UsersController do
  render_views
  let(:user) { FactoryGirl.create(:user, :admin => admin) }
  let(:administrator) { FactoryGirl.create(:administrator) }
  let(:banned_user) { FactoryGirl.create(:user) }

  before(:each) do
    login_as(user)
    session[:last_admin_action_time] = Time.now
    session[:current_admin_id] = administrator.id
 end

  describe 'banning users' do
    context 'as an administrator' do
      let(:admin) { true }

      before(:each) do
        User.should_receive(:ban!).once           # I want something like this
                                                  # on @user in the controller
        post :tos_ban, :id => banned_user.login
      end

      it 'bans the right user' do
        assigns(:user).should eq(banned_user)
      end
    end
  end
end

EDIT:

So, after a little RTFMing -- via the RSpec Book -- I figured out that I need to be using mocks:

it 'bans the user' do
  banned_user = mock_model(User)
  User.stub(:find_by_login).and_return(banned_user)
  banned_user.should_receive(:ban!)
  banned_user.should_receive(:display_name)
  post :tos_ban, :id => banned_user.login
end

Upvotes: 0

Views: 900

Answers (1)

gabrielrotbart
gabrielrotbart

Reputation: 11

banned_user.should_receive(:ban!)

In your controller you assign a reference of the record (an instance of User) to your instance variable. You want to refer to that instance (not the User object nor the variable) to make your assertions.

Upvotes: 1

Related Questions