0

我正在尝试为我继承的 ActiveAdmin 控制器编写测试,但在检查实例变量是否正在调用方法时遇到问题。我想要的行为是调用该方法的副作用,所以我想确保它被调用。

这是控制器:

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

而且,我的规格:

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

编辑:

因此,在通过 RSpec Book 进行一些 RTFMing 之后,我发现我需要使用模拟:

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
4

1 回答 1

1

banned_user.should_receive(:ban!)

在您的控制器中,您将记录的引用(用户的实例)分配给您的实例变量。您想引用该实例(不是 User 对象或变量)来做出断言。

于 2013-07-22T09:35:14.703 回答