Skip to content

Instantly share code, notes, and snippets.

View MaryKuz's full-sized avatar

Maria Kuz MaryKuz

View GitHub Profile
@MaryKuz
MaryKuz / Create UserDecorator
Created March 28, 2019 11:42
Create UserDecorator
class UserDecorator < Draper::Decorator
delegate_all
def as_json *args
{
name: name,
email: email
}
end
end
@MaryKuz
MaryKuz / Write the Test
Created March 28, 2019 11:40
Write the test
require 'rails_helper'
RSpec.describe Api::UsersController, type: :controller do
it { should route(:post, 'api/user').to(action: :create) }
describe '#create.json' do
let(:params) do
{
name: 'Test name',
email: 'test@test.com',
@MaryKuz
MaryKuz / Action Method in ApplicationController
Created March 28, 2019 11:39
Action method in ApplicationController
def create
build_resource
resource.save!
end
@MaryKuz
MaryKuz / Create the Controller
Created March 28, 2019 11:37
Create the controller users_controller.rb
class Api::UsersController < ApplicationController
private
def build_resource
@user = User.new resource_params
end
def resource
@user
end
@MaryKuz
MaryKuz / Create Singleton Resource
Created March 28, 2019 11:35
Create singleton resource
Rails.application.routes.draw do
namespace :api do
...
resource :user, only: [:create]
end
end
@MaryKuz
MaryKuz / Cover New Model with Tests
Created March 28, 2019 11:34
Cover new model with tests
require 'rails_helper'
RSpec.describe User, type: :model do
it { should have_secure_password }
it { should validate_presence_of :name }
it { should validate_presence_of :email }
it { should validate_uniqueness_of(:email).case_insensitive }
@MaryKuz
MaryKuz / Write Validations in the User Model
Created March 28, 2019 11:32
Write validations in the model User
class User < ActiveRecord::Base
has_secure_password
validates :name, presence: true
validates :email, presence: true, uniqueness: { case_sensitive: false }, email: true
end
@MaryKuz
MaryKuz / Adding Code Line
Created March 28, 2019 11:30
Adding code line
class User < ActiveRecord::Base
has_secure_password
end
@MaryKuz
MaryKuz / Correct the test
Created March 28, 2019 10:16
Correct the test spec/models/product
RSpec.describe Product, type: :model do
it { should be_a PgSearch }
describe '.search_by' do
let(:relation) { double }
before { expect(Product).to receive(:page).with(1).and_return(relation) }
context do
it { expect { Product.search_by 'page' => 1 }.to_not raise_error }
@MaryKuz
MaryKuz / Correct the .search_by method
Created March 28, 2019 10:14
Correct the .search_by method
def search_by params = {}
params = params.try(:symbolize_keys) || {}
collection = page(params[:page])
if params[:term].present?
collection = collection.where('name ILIKE ?', "#{ params[:term] }%")
end
if params[:name].present?