Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mock SDK for testing purposes #65

Open
sebak94 opened this issue Aug 30, 2024 · 1 comment
Open

Mock SDK for testing purposes #65

sebak94 opened this issue Aug 30, 2024 · 1 comment

Comments

@sebak94
Copy link

sebak94 commented Aug 30, 2024

Hi there! I'm using the include Clerk::Authenticatable in my controllers and a before_action filter to require authentication. How can I mock the SDK or the Rack middleware to test my controllers with Rspec?

@FinnLawrence
Copy link

Hey @sebak94 since nobody from Clerk has responded to this, I have set up a few little helpers for myself that I can share:

1. Mock the call to the jwks endpoint

Add a copy of the JSON response body of an authorized request to https://api.clerk.dev/v1/jwks to your Rails secrets for test environment. I got this by recording a full test with the VCR gem and taking the response body.

Add a stub to Rspec for this endpoint - I never wanted this call to be made so I put it in my rails_helper.rb.

# spec/rails_helper.rb
RSpec.configure do |config|
  # Other config
  # ...

  # Stub requests to Clerk's jwks and user endpoints
  config.before do
    stub_request(:get, "https://api.clerk.dev/v1/jwks")
      .to_return(
        status: 200,
        body: Rails.application.credentials.dig(:clerk, :test_jwks_response),
        headers: {
          "Content-Type" => "application/json",
          "Clerk-Api-Version" => "2021-02-05"
        }
      )
  end
end

2. Set up a shared context for auth

I add two files to my /spec/fixtures folder for each user I want to use in my test suite:

  1. /bearer_tokens/user_abcd1234.jwt - a valid bearer token I grabbed for that user.
  2. /clerk_users/user_abcd1234.json - the API response to the Clerk user endpoint for that user.

Then my shared context can look like this:

# spec/support/shared_contexts/api_user_context.rb
RSpec.shared_context "with authorized api user" do
  let!(:bearer_token) { read_token_fixture("user_2efKLqLOWIcsBLrJGPCKkR8bgyS") }
  let!(:headers) do
    {
      "Authorization" => "Bearer #{bearer_token[:encoded]}",
      "Accept" => "application/json",
      "Content-Type" => "application/json"
    }
  end

  def read_token_fixture(fixture_name)
      token = File.read("spec/fixtures/bearer_tokens/#{fixture_name}.jwt").chomp
      decoded = JWT.decode(token, nil, false)[0]

      {
        encoded: token,
        user_id: decoded["sub"],
        session_id: decoded["sid"],
        valid_from: Time.zone.at(decoded["nbf"]),
        expires_at: Time.zone.at(decoded["exp"])
      }
    end

  before do
    Timecop.travel(bearer_token[:valid_from])

    stub_request(:get, "https://api.clerk.dev/v1/users/#{bearer_token[:user_id]}")
      .to_return(
        status: 200,
        body: File.read("spec/fixtures/clerk_users/#{bearer_token[:user_id]}.json").chomp,
        headers: {
          "Content-Type" => "application/json"
        }
      )
  end

  after do
    Timecop.return
  end
end

In fact, the read_token_fixture is in a separate bearer_token_helper.rb file that I include, but putting it all together here for you.

This snippet includes setting the time to the window when the bearer token is valid before/after the spec as well, using the Timecop gem.

When you put it all together, it means I can add include_context "with authorized api user" at the top of my request specs and the auth is all stubbed out as long as I include the headers, e.g.

get  "/your/api/path", headers: headers

And you can also use the variables from the bearer token for your factories etc, for example:

let(:api_user) { create(:user, clerk_user_id: bearer_token[:user_id]) }

Hope that helps, let me know if you have any questions!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants