我正在尝试为我继承的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
修改
所以,经过一点点RTFMing - 通过RSpec Book - 我发现我需要使用模拟:
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
答案 0 :(得分:1)
banned_user.should_receive(:ban!)
在您的控制器中,您将记录的引用(User的实例)分配给您的实例变量。您想引用该实例(不是User对象,也不是变量)来进行断言。