Skip to content

Instantly share code, notes, and snippets.

@michaelpri10
Created April 14, 2016 18:18
Show Gist options
  • Save michaelpri10/601c564562bb6003298943c342f4d94a to your computer and use it in GitHub Desktop.
Save michaelpri10/601c564562bb6003298943c342f4d94a to your computer and use it in GitHub Desktop.
Part of the code for my blog
class Post < ActiveRecord::Base
belongs_to :user, -> { where admin: true }
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :title, presence: true
validates :content, presence: true
end
# actually named spec/models/post.rb, but I can't have duplicate file names here
FactoryGirl.define do
factory :post do |p|
p.title Faker::Lorem.sentence(4)
p.content Faker::Lorem.sentence(100)
end
end
require 'rails_helper'
RSpec.describe Post, type: :model do
before do
@user_a = FactoryGirl.create(:user, username: 'michael', email: 'michael@example.com', admin: true)
@user_b = FactoryGirl.create(:user, username: 'joe', email: 'joe@example.com', admin: false)
end
it 'has a valid factory' do
FactoryGirl.create(:post, user: @user_a).should be_valid
end
it 'is invalid without a title' do
FactoryGirl.build(:post, title: "", user: @user_a).should_not be_valid
end
it 'is invalid without content' do
FactoryGirl.build(:post, content: "", user: @user_a).should_not be_valid
end
it 'is invalid without a user' do
FactoryGirl.build(:post, user: nil)
end
it 'orders by highest id' do
post_a = @user_a.posts.create!(content: Faker::Lorem.sentence(100), title: Faker::Lorem.sentence(4))
post_b = @user_a.posts.create!(content: Faker::Lorem.sentence(100), title: Faker::Lorem.sentence(4))
expect(Post.all).to eq([post_b, post_a])
end
# test that fails
it 'should not be created if the user is not admin' do
FactoryGirl.build(:post, user: @user_b).should_not be_valid
end
end
class PostsController < ApplicationController
before_action :admin_user, only: [:new, :create, :edit, :update, :destroy]
def index
@posts = Post.paginate(page: params[:page])
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Blog post created!"
redirect_to blog_url
else
render 'new'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
flash[:success] = "Blog post updated!"
redirect_to @post
else
redirect_to action: :edit
end
end
def destroy
Post.find(params[:id]).destroy
flash[:success] = "Blog post deleted"
redirect_to blog_url
end
private
def post_params
params.require(:post).permit(:title, :content)
end
def admin_user
redirect_to(blog_url) unless current_user.admin?
end
end
FactoryGirl.define do
factory :user do |u|
u.password 'test_password'
u.password_confirmation 'test_password'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment