2016-12-28 2 views
0

devise_auth_token을 사용하여 API 사용자를 인증합니다. 각 테스트를 실행하기 전에 사용자를 인증하고 싶지만 401 오류가 계속 발생합니다. Postman을 올바른 헤더로 끝점에 사용하면 작동하지만 테스트 중에는 작동하지 않습니다.RSpec : devise_auth_token으로 테스트하기 전에 인증

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 
+0

'before (: each) '블록에서'sign_in @ user'를 사용할 수 없습니까? –

답변

0

당신은 당신이 /spec/rails_helper

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

당신은를 사용할 수 있습니다에 다음 항목이 있는지 확인하는 도우미 방법

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

을 사용할 수 있습니다. 다음은 Rspec 예제입니다.

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