ijt1ia
Last Updated: January 22, 2019
·
1.7K
· robguilfoyle

Testing with Auth0 and RSpec in Rails & Ember-CLI

Intro

http://auth0.com is a Authentication & Authorization as a service. Its basically Devise, on steroids, in the cloud.

Setup instructions for auth0 and rails & Ember:

https://auth0.com/docs/quickstart/spa/emberjs/rails

Testing

Auth0 provides authentication by passing a JWT. On the rails side it uses a gem called Knock to handle parsing the JWT and passing it to Auth0 for auth. In order to test you have to stub out this call. Here is code to add to your spec/support/auth0.rb file in order to test with it.

def setup_knock
  request.headers['authorization'] = 'Bearer JWTTOKEN'
  knock = double("Knock")
  user = create(:user)
  yield user if block_given?
  allow(knock).to receive(:current_user).and_return(user)
  allow(knock).to receive(:validate!).and_return(true)
  allow(Knock::AuthToken).to receive(:new).and_return(knock)
end

The yield user if block_given? is just a helper that allows you to do setup to the user if it needs things like roles or any other association. The implementation looks like this:

someapispec.rb

before(:each) do
  setup_knock do |user|
    create(:post, user: user, title: 'Some Blog Post')
  end
end