我正在使用devise_auth_token
gem进行用户身份验证,我正在创建一个模拟“stackoverflow”站点(本站点)的rails-api,因此我的控制器位于命名空间'api'下,并且他们的一些动作要求用户首先登录才能继续(创建问题,答案或投票)。
当我在'Questions_controller_test'中使用'sign_in'方法时,它返回给定用户的id但是'@ controller.api_user_signed_in?'返回始终为false,表示没有用户已登录,因此测试失败。
任何人都可以提出处理这个问题的建议,非常感谢。 这是我的一个controllers_test
require 'test_helper'
require 'devise_token_auth'
class QuestionsControllerTest < ActionController::TestCase
def setup
@controller = Api::QuestionsController.new
@current_user = users(:confirmed_email_user)
@current_user.save!
@auth_headers = @current_user.create_new_auth_token
@result = sign_in @current_user
Ability.new(@current_user)
@token = @auth_headers['access-token']
@client_id = @auth_headers['client']
@expiry = @auth_headers['expiry']
age_token(@current_user, @client_id)
end
#========================================================
test 'Get #index' do
# this test passes
get :index
assert_response :ok
end
test 'Post #create' do
# this test fails cause the controller.current_api_user == nil
post :create , params: {title: 'Q1', description: 'sjdfsdfs'}, headers: @auth_headers, auth_token: @current_user.auth_token
assert_response :created
end
end
并且test_helper是
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'capybara/rails'
require 'devise'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
def age_token(user, client_id)
if user.tokens[client_id]
user.tokens[client_id]['updated_at'] = Time.now - (DeviseTokenAuth.batch_request_buffer_throttle + 50.seconds)
user.save!
end
end
def expire_token(user, client_id)
if user.tokens[client_id]
user.tokens[client_id]['expiry'] = (Time.now - (DeviseTokenAuth.token_lifespan.to_f + 10.seconds)).to_i
user.save!
end
end
# Add more helper methods to be used by all tests here...
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
# Reset sessions and driver between tests
# Use super wherever this method is redefined in your individual test classes
def teardown
Capybara.reset_sessions!
Capybara.use_default_driver
end
end
class ActionController::TestCase
include Warden::Test::Helpers
include Devise::TestHelpers
def setup
@request.env['devise.mapping'] = Devise.mappings[:user]
end
end
end
答案 0 :(得分:0)
我通过存根user_sign_in解决了这个问题?来自devise_auth_token gem的辅助方法
allow(controller).to receive(:ensure_sign_in)
&#34; ensure_sign_in&#34; method是一个调用上面的devise_auth_token帮助方法的before动作&#34;
及其现在的工作:)