2016-12-28 27 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/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 

に次のエントリがあることを確認してくださいあなたのテストではです。ここにRspecの例を示します。

関連する問題