2

我有一个控制器,其索引操作受密码保护:

class Admin::UsersController < Admin::BaseController
  before_action :signed_in_user

  def index
    @users = User.all
  end
end

我有一个测试:

test "should get index" do
  get :index
  assert_response :success
  assert_not_nil assigns(:users)
end

测试失败,因为用户在运行时被重定向到登录页面:

def signed_in_user
  unless signed_in?      
    redirect_to signin_url, notice: "Please sign in."
  end
end

def signed_in?
  !current_user.nil?
end

def current_user
  @current_user ||= User.find_by_remember_token(cookies[:remember_token])
end

def current_user=(user)
  @current_user = user
end

def sign_in(user)
  cookies.permanent[:remember_token] = user.remember_token
  self.current_user = user
end

def current_user?(user)
  user == current_user
end

我知道我可以使用 capybara 访问登录页面并登录测试用户,但根据我的经验,这通常会导致测试套件需要很长时间才能运行,所以我希望可能有一种快速而肮脏的方法来做到这一点使用会话:

test "should get index" do
  get :index, { }, { remember_token: users(:one).remember_token }
  assert_response :success
  assert_not_nil assigns(:users)
end

# I also tried the following:
test "should get index" do
  get :index, { }, { current_user: users(:one) }
  assert_response :success
  assert_not_nil assigns(:users)
end

我希望上面的内容能神奇地让我的测试用户登录,但没有,我们仍然被重定向到测试失败的登录页面。

做这种事情的正确方法是什么?它快把我逼疯了。

4

1 回答 1

0

已修复,感谢这个问题。我只需要:

setup do
  @user = users(:one)
  # since I am using cookies, I just need to set them here
  @request.cookies['remember_token'] = @user.remember_token
end

# no need to pass anything to the get method
test "should get index" do
  get :index
  assert_response :success
  assert_not_nil assigns(:users)
end
于 2013-03-03T16:35:17.317 回答