require 'spec_helper' require 'webmock/rspec' describe AuthSession do let(:session) { Fabricate :auth_session } let(:response) { double('response', code: 201, parsed_response: 'some_response') } describe '#initialize' do it 'sets the core_host instance attribute' do session = AuthSession.new core_host: 'some_core_host' expect(session.core_host).to eq('some_core_host') end it 'defaults the core_host to the CORE_HOST env variable' do orginal_env_core_host = ENV['CORE_HOST'] ENV['CORE_HOST'] = 'some_env_core_host' session = AuthSession.new ENV['CORE_HOST'] = orginal_env_core_host expect(session.core_host).to eq('some_env_core_host') end it 'sets the default timeout' do session = AuthSession.new timeout: 30 expect(session.default_timeout).to eq 30 end it 'defaults the default timeout to nil' do session = AuthSession.new expect(session.default_timeout).to be_nil end end describe '#get' do it 'performs a get request' do allow(session).to receive(:basic_auth).and_return(username: 'some_username', password: 'some_password') allow(session).to receive(:headers).and_return(some: 'header') expect(HTTParty).to receive(:get).with('http://core.dev/api/v1/some_path.json', query: {some: 'param'}, headers: {some: 'header'}, basic_auth: {username: 'some_username', password: 'some_password'}, timeout: nil) .and_return(response) session.get '/some_path', some: 'param' end it 'returns the response on sucess status' do stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return( status: 201, body: '{ "success": true }', headers: { 'Content-Type' => 'application/json' }) expect(session.get('/some_path')['success']).to be_truthy end it 'returns the response on a 422 status' do stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return( status: 422, body: '{ "errors": { "column": ["wrong"] } }', headers: { 'Content-Type' => 'application/json' }) expect(session.get('/some_path')['errors']['column']).to eq ["wrong"] end it 'raises a no_session error when response is 401 with a no_session response' do stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return( status: 401, body: '{ "no_session": true }', headers: { 'Content-Type' => 'application/json' }) expect { session.get '/some_path' }.to raise_error(NoSession) end it 'raises a unauthorized error when response is 401 without a no_session response' do stub_request(:get, 'http://core.dev/api/v1/some_path.json?').to_return( status: 401, body: '', headers: { 'Content-Type' => 'application/json' }) expect { session.get '/some_path' }.to raise_error(Unauthorized) end it 'throws an error if the reponse is not within the 200 range' do allow(response).to receive(:code).and_return(500) allow(HTTParty).to receive(:get).and_return(response) expect { session.get '/some_path' }.to raise_error(RuntimeError, 'some_response') end it 'returns the response' do allow(HTTParty).to receive(:get).and_return(response) expect(session.get '/some_path').to eq(response) end end end