RSpec:使用devise_auth_token进行验证之前验证 [英] RSpec: Authenticating before test with devise_auth_token
本文介绍了RSpec:使用devise_auth_token进行验证之前验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 devise_auth_token 为API验证用户。在每次测试运行之前,我想对用户进行身份验证,但是会出现401错误。当我使用postman到终端与正确的标题,它的工作,但无法在测试期间工作。
I am using devise_auth_token to authenticate users for an API. I would like to authenticate users before each test is run, but keep getting a 401 error. When I use postman to the endpoint with the correct headers, it works, but fails to work during tests.
before(:each) do
@user = FactoryGirl.create(:user)
end
def get_auth
headers = @user.create_new_auth_token
auth = Hash.new
auth["client"] = headers["client"]
auth["access-token"] = headers["access-token"]
auth["uid"] = headers["uid"]
auth["expiry"] = headers["expiry"]
return auth
end
it "auth user should return success" do
get 'get_tasks_for_user', params: {uid: @user.uid}, headers: get_auth
expect(response).to have_http_status(200)
end
RSpec
TasksController auth user should return success
Failure/Error: expect(response).to have_http_status 200
expected the response to have status code 200 but it was 401
推荐答案
您可以使用帮助方法
#/spec/support/helpers/session_helper.rb
module SessionHelper
def set_request_headers(resp)
{ 'ACCEPT' => "application/json",
'Content-Type' => "application/json",
'access-token' => resp['access-token'],
'token-type' => resp['token-type'],
'client' => resp['client'],
'expiry' => resp['expiry'],
'uid' => resp['uid']
}
end
def subdomain_login(uid, password, subdomain)
request_params = {
'email' => uid,
'password' => password
}
host! "#{subdomain}.lvh.me"
post "/portal/auth/sign_in", params: request_params
return set_request_headers(response.headers)
end
end
确保您的 / spec / rails_helper $ c中有以下条目$ c>
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
config.include SessionHelper, :type => :request
end
您可以使用 subdomain_login
在你的测试。这是一个Rspec示例。
You can use subdomain_login
in your tests. Here is an Rspec example.
post '/portal/system/locations', params: request_params.to_json,
headers: subdomain_login(user_id, password, subdomain)
这篇关于RSpec:使用devise_auth_token进行验证之前验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文