Skip to content

Instantly share code, notes, and snippets.

describe 'WidgetsController endpoints' do
describe 'GET /widgets' do
context 'with authenticated user' do
# ...
end
context 'without authenticated user' do
it 'returns a 401 - Unauthorized response' do
get(widgets_url, {}, accept_headers)
constraints AuthenticatedConstraint.new do
resources :widgets
end
GET /widgets
Authorization: Token token=<my_token_here>
# app/models/user.rb
def reset_token!
AuthenticationToken.reset(user: self)
end
# app/services/authentication_token.rb
class AuthenticationToken
attr_reader :user
class SignUpUser
attr_reader :user_attrs
def initialize(user_attrs)
@user_attrs ||= user_attrs
end
def self.perform(user_attrs)
new(user_attrs).perform
end
# app/services/sign_up_user.rb
def sign_up_user
user.tap do |user|
user.reset_token!
user.save! # raise error if validation fails
end
end
# app/controllers/v1/users_controller.rb
# app/controllers/v1/users_controller.rb
def create
user = SignUpUser.perform(user_params)
if user.save
render json: user, serializer: AuthenticationSerializer, root: :user
else
render json: { errors: user.errors.full_messages },
status: :unprocessable_entity
# /spec/requests/v1/users_requests_spec.rb
context 'with errors' do
context 'such as a pre-existing email' do
it 'returns a 422 response and JSON for errors' do
existing_user = create(:user)
user_attributes = {
user: {
email: existing_user.email,
# app/serializers/authentication_serializer.rb
class AuthenticationSerializer < BaseSerializer
attributes :email, :authentication_token, :authentication_token_expires_at
end
# app/serializers/base_serializer.rb
class BaseSerializer < ActiveModel::Serializer
attributes :id, :created_at, :updated_at
embed :ids
end