RSpec:使用devise_auth_token进行测试前进行身份验证

时间:2016-12-28 22:29:10

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用辅助方法

#/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)