我遇到问题,让Warden的哈希出现在我的RSpec测试中的请求哈希中。当我在开发模式下运行我的应用程序时,Warden键就在那里,但在测试环境中,一切都是零。我在下面包含了我的基本rspec配置。如果有人有任何想法,我错了,我真的很想知道,我几乎整整一天都在摆弄它。
在开发模式下运行时,会找到Warden,但在测试模式下运行env['warden']
始终为nil
以下是我在开发模式期间在请求对象内部使用warden哈希时获得的示例:
request['warden']
=> Warden::Proxy:70272688271480 @config={:default_scope=>:default, :scope_defaults=>{}, :default_strategies=>{:_all=>[:password, :basic]}, :intercept_401=>true, :failure_app=>GrapeApe::BadAuthentication}
这是我在测试期间检查请求对象内的warden哈希时得到的结果:
request['warden']
=> nil
Spec Helper文件
require 'rubygems'
ENV["RACK_ENV"] ||= 'test'
require 'rack/test'
require 'capybara/rspec'
require 'factory_girl'
require File.expand_path("../../config/environment", __FILE__)
FactoryGirl.find_definitions
RSpec.configure do |config|
config.mock_with :rspec
config.expect_with :rspec
config.include Capybara::DSL
config.include Rack::Test::Methods
config.include Warden::Test::Helpers
config.after :each do
Warden.test_reset!
end
end
Capybara.configure do |config|
config.app = GrapeApe::App.new
config.server_port = 9293
end
示例规范,其中warden应该抛出403响应,因为用户尚未经过身份验证。
it "should get a specfic sketch" do
get "/api/v1/sketches/#{@sketch.id}"
JSON.parse(last_response.body)['files'].should == ["foo"]
end
示例错误:
Failure/Error: JSON.parse(last_response.body)['files'].should == ["foo"]
JSON::ParserError:
756: unexpected token at 'undefined method `authenticated?' for nil:NilClass'
检查监护人密钥的相关Grape辅助方法
module GrapeApe
module Helpers
def warden
env['warden']
end
def authenticated
if warden.authenticated?
return true
elsif params[:access_token] and
User.find_for_token_authentication("access_token" => params[:access_token])
return true
else
error!('401 Unauthorized', 401)
end
end
def current_user
warden.user || User.find_for_token_authentication("access_token" => params[:access_token])
end
def authenticated_user
authenticated
error!('401 Unauthorized', 401) unless current_user
end
end
end