【问题标题】:RSpec: Authenticating before test with devise_auth_tokenRSpec:在测试前使用 devise_auth_token 进行身份验证
【发布时间】:2017-05-13 05:49:45
【问题描述】:

我正在使用devise_auth_token 对 API 的用户进行身份验证。我想在每次测试运行之前对用户进行身份验证,但不断收到 401 错误。当我使用邮递员到具有正确标头的端点时,它可以工作,但在测试期间无法工作。

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

【问题讨论】:

  • 你不能在before(:each)块中使用sign_in @user吗?

标签: ruby-on-rails ruby testing rspec devise


【解决方案1】:

你可以使用辅助方法

#/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 中有以下条目

Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
RSpec.configure do |config|
 config.include SessionHelper, :type => :request
end

您可以在测试中使用subdomain_login。这是一个 Rspec 示例。

post '/portal/system/locations', params: request_params.to_json,
  headers: subdomain_login(user_id, password, subdomain)

【讨论】:

    猜你喜欢
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2016-05-05
    相关资源
    最近更新 更多