Search code examples
rspecgraphqlfaradayfaraday-oauth

Rspec: Getting Omniauth/oauth0 working with a Faraday Request


I am trying to test a graphql request with Faraday, but I first need to authenticate with omniauth/auth0.

I got it to authenticate by setting

   def sign_in(user, invalid=false, strategy = :auth0)
      invalid ?  mock_invalid_auth_hash : mock_valid_auth_hash(user)
      Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[strategy.to_sym]
      visit "/auth/#{strategy.to_s}/callback"
   end

But when graphql gets tested it totally loses that cookie since this is a brand new request:

require 'graphlient'

RSpec.shared_context "GraphQL Client", shared_context: :metadata do
  let(:client) do
    Graphlient::Client.new('https://www.example.org/graphql') do |client|
      client.http do |h|
        h.connection do |c|
          c.use Faraday::Adapter::Rack, app
        end
      end
    end
  end
end

How can I set the environment via Faraday to be authenticated before it connects to GraphQL? Or is there a better way to test GraphQL?


Solution

  • I figured this out by not using graphlient and faraday (though I didn't try it once I figured out what was wrong, so it may still work, but here's an alternative).

    Changed the sign_in method to a get request instead of visit:

    spec/support/features/session_helpers.rb

    def sign_in(user, invalid=false, strategy = :auth0)
      invalid ?  mock_invalid_auth_hash : mock_valid_auth_hash(user)
      get "/auth/#{strategy.to_s}"
      Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[strategy.to_sym]
      get "/auth/#{strategy.to_s}/callback"
    end
    

    And in my rspec request test I did like so (I'll include a whole test example in case it helps anyone):

    spec/support/graphql/client.rb

    RSpec.shared_context "GraphQL Client", shared_context: :metadata do
      let(:user) { create(:user) }
    
      let(:post_query_as_user) do
        sign_in(user)
        params = { query: query }
        post "/graphql", params: params
      end
    
      def data
        JSON.parse(response.body)["data"]
      end
    end
    

    spec/graphql/queries/current_user_queries_spec.rb

    require 'rails_helper'
    
    RSpec.describe 'GraphQL::Queries::CurrentUser', type: 'request' do
      include_context 'GraphQL Client'
      let(:query) do
        <<-GRAPHQL
          {
            current_user {
              id
              first_name
            }
          }
        GRAPHQL
      end
    
      it 'returns the current user with all user attributes' do
        post_query_as_user
        current_user = data["current_user"]
        expect(current_user["first_name"]).to eq(user.first_name)
      end
    end