对于假设用户已经过身份验证的控制器,我该如何编写测试?
我可能不需要继续测试登录功能,所以最好只注入一个用户或我的身份验证假定的某种方式?
我的application_controller包含一个模块“current_user”。
module CurrentUser
def self.included(base)
base.send :helper_method, :current_user
end
def current_user
... # returns a User model instance
end
end
class ApplicationController < ActionController::Base
include CurrentUser
然后我有一个管理控制器,它有一个before_action方法,可以确保current_user存在。
答案 0 :(得分:1)
您可以通过编写问题轻松实现这一点,并将其包含在作为控制器的每个规范中,在此关注中我们支持一些实用程序方法来登录系统。
所以代码就像:
<强>规格/支持/ controller_authentication_helper.rb 强>
module ControllerAuthenticationHelper extend ActiveSupport::Concern
module ClassMethods
def login_user
before do
# I expect you are using Devise here, if not, just modify below line
request.env['devise.mapping'] = Devise.mappings[:user]
@current_user = FactoryGirl.create(:user, :confirmed, :verified)
sign_in @current_user
end
end
end
end
RSpec.configure do |config|
config.include ControllerAuthenticationHelper, type: :controller
end
所以现在测试很简单:
require 'rails_helper'
describe MyController, type: :controller do
# Use this method to login
login_user
# Now you can access current_user anywhere in your test
end
现在一切都变得简单!这个想法来自这个source code的Devise