Commit 29026b02 by tady

robocop

parent 29a39cc2
LineLength:
Max: 159
NumericLiterals:
Enabled: false
Documentation:
Enabled: false
WordArray:
Enabled: false
MethodLength:
Max: 30
IfUnlessModifier:
Enabled: false
CyclomaticComplexity:
Max: 10
...@@ -70,6 +70,10 @@ group :development do ...@@ -70,6 +70,10 @@ group :development do
# profiler # profiler
gem 'rack-mini-profiler' gem 'rack-mini-profiler'
# rubocop
gem 'rubocop'
gem 'guard-rubocop'
end end
group :development, :test do group :development, :test do
......
...@@ -45,6 +45,7 @@ GEM ...@@ -45,6 +45,7 @@ GEM
ancestry (2.0.0) ancestry (2.0.0)
activerecord (>= 3.0.0) activerecord (>= 3.0.0)
arel (4.0.1) arel (4.0.1)
ast (1.1.0)
atomic (1.1.14) atomic (1.1.14)
bcrypt-ruby (3.1.2) bcrypt-ruby (3.1.2)
better_errors (1.1.0) better_errors (1.1.0)
...@@ -104,6 +105,9 @@ GEM ...@@ -104,6 +105,9 @@ GEM
guard-rspec (4.2.0) guard-rspec (4.2.0)
guard (>= 2.1.1) guard (>= 2.1.1)
rspec (>= 2.14, < 4.0) rspec (>= 2.14, < 4.0)
guard-rubocop (1.0.0)
guard (~> 2.0)
rubocop (~> 0.10)
guard-spring (0.0.4) guard-spring (0.0.4)
guard guard
spring spring
...@@ -151,7 +155,11 @@ GEM ...@@ -151,7 +155,11 @@ GEM
oauth2 (~> 0.8.0) oauth2 (~> 0.8.0)
omniauth (~> 1.0) omniauth (~> 1.0)
orm_adapter (0.5.0) orm_adapter (0.5.0)
parser (2.0.0)
ast (~> 1.1)
slop (~> 3.4, >= 3.4.5)
polyglot (0.3.3) polyglot (0.3.3)
powerpack (0.0.9)
premailer (1.7.9) premailer (1.7.9)
css_parser (>= 1.1.9) css_parser (>= 1.1.9)
htmlentities (>= 4.0.0) htmlentities (>= 4.0.0)
...@@ -179,6 +187,7 @@ GEM ...@@ -179,6 +187,7 @@ GEM
activesupport (= 4.0.2) activesupport (= 4.0.2)
rake (>= 0.8.7) rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0) thor (>= 0.18.1, < 2.0)
rainbow (1.1.4)
rake (10.1.1) rake (10.1.1)
rb-fsevent (0.9.3) rb-fsevent (0.9.3)
rb-inotify (0.9.3) rb-inotify (0.9.3)
...@@ -202,6 +211,10 @@ GEM ...@@ -202,6 +211,10 @@ GEM
rspec-core (~> 2.14.0) rspec-core (~> 2.14.0)
rspec-expectations (~> 2.14.0) rspec-expectations (~> 2.14.0)
rspec-mocks (~> 2.14.0) rspec-mocks (~> 2.14.0)
rubocop (0.15.0)
parser (~> 2.0)
powerpack (~> 0.0.6)
rainbow (>= 1.1.4)
sass (3.2.13) sass (3.2.13)
sass-rails (4.0.1) sass-rails (4.0.1)
railties (>= 4.0.0, < 5.0) railties (>= 4.0.0, < 5.0)
...@@ -264,6 +277,7 @@ DEPENDENCIES ...@@ -264,6 +277,7 @@ DEPENDENCIES
factory_girl_rails factory_girl_rails
faraday faraday
guard-rspec guard-rspec
guard-rubocop
guard-spring guard-spring
jbuilder jbuilder
mail mail
...@@ -275,6 +289,7 @@ DEPENDENCIES ...@@ -275,6 +289,7 @@ DEPENDENCIES
rails (~> 4.0.2) rails (~> 4.0.2)
redcarpet! redcarpet!
rspec-rails rspec-rails
rubocop
sass-rails sass-rails
sdoc sdoc
spring spring
......
...@@ -10,3 +10,8 @@ guard :rspec, spring: true do ...@@ -10,3 +10,8 @@ guard :rspec, spring: true do
watch('config/routes.rb') { 'spec/routing' } watch('config/routes.rb') { 'spec/routing' }
watch('app/controllers/application_controller.rb') { 'spec/controllers' } watch('app/controllers/application_controller.rb') { 'spec/controllers' }
end end
guard :rubocop, cli: ['--rails', '--auto-correct'] do
watch(%r{.+\.rb$})
watch(%r{(?:.+/)?\.rubocop\.yml$}) { |m| File.dirname(m[0]) }
end
...@@ -9,5 +9,4 @@ class ApplicationController < ActionController::Base ...@@ -9,5 +9,4 @@ class ApplicationController < ActionController::Base
redirect_to root_path redirect_to root_path
end end
end end
end end
class HomeController < ApplicationController class HomeController < ApplicationController
skip_before_action :require_login skip_before_action :require_login
def top def top
...@@ -9,6 +8,4 @@ class HomeController < ApplicationController ...@@ -9,6 +8,4 @@ class HomeController < ApplicationController
render template: 'home/login' render template: 'home/login'
end end
end end
end end
...@@ -2,7 +2,6 @@ require 'nkf' ...@@ -2,7 +2,6 @@ require 'nkf'
require 'rv/mailer' require 'rv/mailer'
class PostsController < ApplicationController class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy] before_action :set_post, only: [:show, :edit, :update, :destroy]
before_action :require_login before_action :require_login
...@@ -28,7 +27,6 @@ class PostsController < ApplicationController ...@@ -28,7 +27,6 @@ class PostsController < ApplicationController
render layout: false, partial: 'posts/show_fragment' render layout: false, partial: 'posts/show_fragment'
end end
# GET /posts/1 # GET /posts/1
# GET /posts/1.json # GET /posts/1.json
def show def show
...@@ -104,26 +102,26 @@ class PostsController < ApplicationController ...@@ -104,26 +102,26 @@ class PostsController < ApplicationController
end end
private private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through. # Use callbacks to share common setup or constraints between actions.
def post_params def set_post
@post_params ||= begin @post = Post.find(params[:id])
_param_hash = params.require(:post).permit(:title, :body, :tags).to_hash end
# tags_text == 'Javascript,Ruby' # Never trust parameters from the scary internet, only allow the white list through.
tags_text = _param_hash.delete('tags') def post_params
@post_params ||= begin
_param_hash = params.require(:post).permit(:title, :body, :tags).to_hash
tags = tags_text.split(',').map do |_tag_name| # tags_text == 'Javascript,Ruby'
Tag.find_or_create_by(name: _tag_name) tags_text = _param_hash.delete('tags')
end
_param_hash["tag_ids"] = tags.map(&:id)
_param_hash tags = tags_text.split(',').map do |_tag_name|
Tag.find_or_create_by(name: _tag_name)
end end
end _param_hash['tag_ids'] = tags.map(&:id)
_param_hash
end
end
end end
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2 def google_oauth2
# You need to implement the method below in your model (e.g. app/models/user.rb) # You need to implement the method below in your model (e.g. app/models/user.rb)
@user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user) @user = User.find_for_google_oauth2(request.env['omniauth.auth'], current_user)
if @user.persisted? if @user.persisted?
flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google" flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
sign_in_and_redirect @user, :event => :authentication sign_in_and_redirect @user, event: :authentication
else else
session["devise.google_data"] = request.env["omniauth.auth"] session['devise.google_data'] = request.env['omniauth.auth']
redirect_to new_user_registration_url redirect_to new_user_registration_url
end end
end end
end end
module ApplicationHelper module ApplicationHelper
class HtmlWithPrettyPrint < Redcarpet::Render::HTML class HtmlWithPrettyPrint < Redcarpet::Render::HTML
def postprocess(full_document) def postprocess(full_document)
full_document.gsub("prettyprint", "prettyprint linenums") full_document.gsub('prettyprint', 'prettyprint linenums')
end end
end end
def h_application_format_markdown(text) def h_application_format_markdown(text)
# html_render = HTMLwithCoderay.new(filter_html: true, hard_wrap: true, prettify: true) # html_render = HTMLwithCoderay.new(filter_html: true, hard_wrap: true, prettify: true)
html_render = HtmlWithPrettyPrint.new(:prettify => true) html_render = HtmlWithPrettyPrint.new(prettify: true)
options = { options = {
autolink: true, autolink: true,
space_after_headers: true, space_after_headers: true,
...@@ -18,5 +17,4 @@ module ApplicationHelper ...@@ -18,5 +17,4 @@ module ApplicationHelper
markdown = Redcarpet::Markdown.new(html_render, options) markdown = Redcarpet::Markdown.new(html_render, options)
markdown.render(text).html_safe markdown.render(text).html_safe
end end
end end
module PostsHelper module PostsHelper
# @param {ActiveRecord::Relation} node # @param {ActiveRecord::Relation} node
def h_display_tree(node) def h_display_tree(node)
_html = '<ul>' _html = '<ul>'
...@@ -10,7 +9,7 @@ module PostsHelper ...@@ -10,7 +9,7 @@ module PostsHelper
_html << h_display_tree(_child) _html << h_display_tree(_child)
end end
_html << '</ul>' _html << '</ul>'
_html.html_safe _html.html_safe
end end
end end
...@@ -6,9 +6,9 @@ class Post < ActiveRecord::Base ...@@ -6,9 +6,9 @@ class Post < ActiveRecord::Base
# Named scope # Named scope
def self.build_query(params) def self.build_query(params)
_where_list = self.includes(:author, :tags) _where_list = includes(:author, :tags)
# 空白を一つに変換 # Convert spaces to one space.
query_string = params[:q].gsub(/[\s ]+/, ' ') query_string = params[:q].gsub(/[\s ]+/, ' ')
query_list = query_string.split(' ') query_list = query_string.split(' ')
...@@ -16,17 +16,17 @@ class Post < ActiveRecord::Base ...@@ -16,17 +16,17 @@ class Post < ActiveRecord::Base
query_list.each do |_query| query_list.each do |_query|
case _query case _query
when /^post:(.+)/ when /^post:(.+)/
_where_list = _where_list.where('id = ?', $1) _where_list = _where_list.where('id = ?', Regexp.last_match[1])
when /^title:(.+)/ when /^title:(.+)/
_where_list = _where_list.where('title LIKE ?', "%#{$1}%") _where_list = _where_list.where('title LIKE ?', "%#{Regexp.last_match[1]}%")
when /^body:(.+)/ when /^body:(.+)/
_where_list = _where_list.where('body LIKE ?', "%#{$1}%") _where_list = _where_list.where('body LIKE ?', "%#{Regexp.last_match[1]}%")
when /^@(.+)/ when /^@(.+)/
_where_list = _where_list.where('users.name = ?', $1) _where_list = _where_list.where('users.name = ?', Regexp.last_match[1])
when /^#(.+)/ when /^#(.+)/
_where_list = _where_list.where('tags.name = ?', $1) _where_list = _where_list.where('tags.name = ?', Regexp.last_match[1])
when /^date:(\d+)-(\d+)-(\d+)/ when /^date:(\d+)-(\d+)-(\d+)/
_date = Time.new($1, $2, $3) _date = Time.new(Regexp.last_match[1], Regexp.last_match[2], Regexp.last_match[3])
_where_list = _where_list.where('updated_at > ? AND updated_at < ?', _date, _date + 1.day) _where_list = _where_list.where('updated_at > ? AND updated_at < ?', _date, _date + 1.day)
else else
_where_list = _where_list.where('title LIKE ? OR body LIKE ?', "%#{_query}%", "%#{_query}%") _where_list = _where_list.where('title LIKE ? OR body LIKE ?', "%#{_query}%", "%#{_query}%")
...@@ -34,17 +34,15 @@ class Post < ActiveRecord::Base ...@@ -34,17 +34,15 @@ class Post < ActiveRecord::Base
end end
_where_list _where_list
end end
# generate forked post (not saved) # generate forked post (not saved)
def generate_fork(user) def generate_fork(user)
forked_post = self.clone forked_post = clone
forked_post.title = forked_post.title.gsub(/%Name/, user.name) forked_post.title = forked_post.title.gsub(/%Name/, user.name)
forked_post.title = Time.now.strftime(forked_post.title) # TODO forked_post.title = Time.now.strftime(forked_post.title) # TODO
forked_post.author = user forked_post.author = user
forked_post forked_post
end end
end end
...@@ -3,5 +3,4 @@ class Tag < ActiveRecord::Base ...@@ -3,5 +3,4 @@ class Tag < ActiveRecord::Base
has_many :posts, through: :post_tags has_many :posts, through: :post_tags
has_ancestry has_ancestry
end end
...@@ -5,20 +5,20 @@ class User < ActiveRecord::Base ...@@ -5,20 +5,20 @@ class User < ActiveRecord::Base
# :confirmable, :lockable, :timeoutable and :omniauthable # :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable :recoverable, :rememberable, :trackable, :validatable
devise :omniauthable, :omniauth_providers => [:google_oauth2] devise :omniauthable, omniauth_providers: [:google_oauth2]
has_many :posts has_many :posts
# Device # Device
def self.find_for_google_oauth2(access_token, signed_in_resource=nil) def self.find_for_google_oauth2(access_token, signed_in_resource = nil)
data = access_token.info data = access_token.info
user = User.where(email: data["email"]).first user = User.where(email: data['email']).first
unless user unless user
user = User.create(name: data["name"], user = User.create(name: data['name'],
image_url: data["image"], image_url: data['image'],
email: data["email"], email: data['email'],
password: Devise.friendly_token[0,20] password: Devise.friendly_token[0, 20]
) )
end end
...@@ -33,7 +33,7 @@ class User < ActiveRecord::Base ...@@ -33,7 +33,7 @@ class User < ActiveRecord::Base
# check if google oauth token is expired # check if google oauth token is expired
def google_oauth_token_expired? def google_oauth_token_expired?
self.google_token_expires_at < Time.now google_token_expires_at < Time.now
end end
# refresh google oauth token # refresh google oauth token
...@@ -42,18 +42,17 @@ class User < ActiveRecord::Base ...@@ -42,18 +42,17 @@ class User < ActiveRecord::Base
builder.request :url_encoded builder.request :url_encoded
builder.adapter :net_http builder.adapter :net_http
end end
response = conn.post '/o/oauth2/token', { response = conn.post '/o/oauth2/token',
client_id: ENV["GOOGLE_KEY"], client_id: ENV['GOOGLE_KEY'],
client_secret: ENV["GOOGLE_SECRET"], client_secret: ENV['GOOGLE_SECRET'],
refresh_token: self.google_refresh_token, refresh_token: google_refresh_token,
grant_type: "refresh_token" grant_type: 'refresh_token'
}
res_json = JSON.parse(response.body) res_json = JSON.parse(response.body)
self.update_attributes( update_attributes(
google_auth_token: res_json['access_token'], google_auth_token: res_json['access_token'],
google_token_expires_at: Time.now + res_json['expires_in'].seconds google_token_expires_at: Time.now + res_json['expires_in'].seconds
) )
end end
end end
...@@ -7,8 +7,8 @@ ...@@ -7,8 +7,8 @@
# #
require 'pathname' require 'pathname'
ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile',
Pathname.new(__FILE__).realpath) Pathname.new(__FILE__).realpath)
require 'rubygems' require 'rubygems'
require 'bundler/setup' require 'bundler/setup'
......
...@@ -22,7 +22,6 @@ module Rendezvous ...@@ -22,7 +22,6 @@ module Rendezvous
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :ja config.i18n.default_locale = :ja
# config.action_mailer.delivery_method = :action_gmailer # config.action_mailer.delivery_method = :action_gmailer
config.action_mailer.smtp_settings = { config.action_mailer.smtp_settings = {
smtp_host: 'smtp.gmail.com', smtp_host: 'smtp.gmail.com',
...@@ -32,7 +31,5 @@ module Rendezvous ...@@ -32,7 +31,5 @@ module Rendezvous
# oauth2_token: 'FIXME', # oauth2_token: 'FIXME',
# account: 'FIXME' # account: 'FIXME'
} }
end end
end end
...@@ -28,5 +28,5 @@ Rendezvous::Application.configure do ...@@ -28,5 +28,5 @@ Rendezvous::Application.configure do
config.assets.debug = true config.assets.debug = true
# Devise # Devise
config.action_mailer.default_url_options = { :host => 'localhost:3000' } config.action_mailer.default_url_options = { host: 'localhost:3000' }
end end
...@@ -14,7 +14,7 @@ Rendezvous::Application.configure do ...@@ -14,7 +14,7 @@ Rendezvous::Application.configure do
# Configure static asset server for tests with Cache-Control for performance. # Configure static asset server for tests with Cache-Control for performance.
config.serve_static_assets = true config.serve_static_assets = true
config.static_cache_control = "public, max-age=3600" config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching. # Show full error reports and disable caching.
config.consider_all_requests_local = true config.consider_all_requests_local = true
......
...@@ -41,12 +41,12 @@ Devise.setup do |config| ...@@ -41,12 +41,12 @@ Devise.setup do |config|
# Configure which authentication keys should be case-insensitive. # Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used # These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email. # to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ] config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped. # Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or # These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email. # modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ] config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default. # Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the # It can be set to an array that will enable params authentication only for the
......
Rails.application.config.middleware.use OmniAuth::Builder do Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"],
{ provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'],
:name => "google_oauth2", name: 'google_oauth2',
:scope => "https://mail.google.com/, userinfo.email, userinfo.profile", scope: 'https://mail.google.com/, userinfo.email, userinfo.profile',
access_type: 'offline', access_type: 'offline',
:prompt => "select_account consent", prompt: 'select_account consent',
:image_aspect_ratio => "square", image_aspect_ratio: 'square',
:image_size => 50 image_size: 50
}
end end
...@@ -9,4 +9,5 @@ ...@@ -9,4 +9,5 @@
# Make sure your secret_key_base is kept private # Make sure your secret_key_base is kept private
# if you're sharing your code publicly. # if you're sharing your code publicly.
Rendezvous::Application.config.secret_key_base = 'd8e487b60856000161a94ea764b38e7492512bbbeeca2f4cec068c8cc6618cacb54172ec54afc61675684f01bf02c74bf1e93dfe6971247d75ff001b1584d987' Rendezvous::Application.config.secret_key_base = \
'd8e487b60856000161a94ea764b38e7492512bbbeeca2f4cec068c8cc6618cacb54172ec54afc61675684f01bf02c74bf1e93dfe6971247d75ff001b1584d987'
...@@ -8,8 +8,7 @@ Rendezvous::Application.routes.draw do ...@@ -8,8 +8,7 @@ Rendezvous::Application.routes.draw do
get 'posts/:id/mail' => 'posts#mail', as: 'mail_post' get 'posts/:id/mail' => 'posts#mail', as: 'mail_post'
resources :posts resources :posts
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
# The priority is based upon order of creation: first created -> highest priority. # The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes". # See how all your routes lay out with "rake routes".
......
...@@ -2,8 +2,8 @@ class AddDeviseToUsers < ActiveRecord::Migration ...@@ -2,8 +2,8 @@ class AddDeviseToUsers < ActiveRecord::Migration
def self.up def self.up
change_table(:users) do |t| change_table(:users) do |t|
## Database authenticatable ## Database authenticatable
t.string :email, :null => false, :default => "" t.string :email, null: false, default: ''
t.string :encrypted_password, :null => false, :default => "" t.string :encrypted_password, null: false, default: ''
## Recoverable ## Recoverable
t.string :reset_password_token t.string :reset_password_token
...@@ -13,7 +13,7 @@ class AddDeviseToUsers < ActiveRecord::Migration ...@@ -13,7 +13,7 @@ class AddDeviseToUsers < ActiveRecord::Migration
t.datetime :remember_created_at t.datetime :remember_created_at
## Trackable ## Trackable
t.integer :sign_in_count, :default => 0, :null => false t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at t.datetime :current_sign_in_at
t.datetime :last_sign_in_at t.datetime :last_sign_in_at
t.string :current_sign_in_ip t.string :current_sign_in_ip
...@@ -30,13 +30,12 @@ class AddDeviseToUsers < ActiveRecord::Migration ...@@ -30,13 +30,12 @@ class AddDeviseToUsers < ActiveRecord::Migration
# t.string :unlock_token # Only if unlock strategy is :email or :both # t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at # t.datetime :locked_at
# Uncomment below if timestamps were not included in your original model. # Uncomment below if timestamps were not included in your original model.
# t.timestamps # t.timestamps
end end
add_index :users, :email, :unique => true add_index :users, :email, unique: true
add_index :users, :reset_password_token, :unique => true add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, :unique => true # add_index :users, :confirmation_token, :unique => true
# add_index :users, :unlock_token, :unique => true # add_index :users, :unlock_token, :unique => true
end end
...@@ -44,6 +43,6 @@ class AddDeviseToUsers < ActiveRecord::Migration ...@@ -44,6 +43,6 @@ class AddDeviseToUsers < ActiveRecord::Migration
def self.down def self.down
# By default, we don't want to make any assumption about how to roll back a migration when your # By default, we don't want to make any assumption about how to roll back a migration when your
# model already existed. Please edit below which fields you would like to remove in this migration. # model already existed. Please edit below which fields you would like to remove in this migration.
raise ActiveRecord::IrreversibleMigration fail ActiveRecord::IrreversibleMigration
end end
end end
...@@ -13,54 +13,54 @@ ...@@ -13,54 +13,54 @@
ActiveRecord::Schema.define(version: 20131228110818) do ActiveRecord::Schema.define(version: 20131228110818) do
create_table "post_tags", force: true do |t| create_table 'post_tags', force: true do |t|
t.integer "post_id", null: false t.integer 'post_id', null: false
t.integer "tag_id", null: false t.integer 'tag_id', null: false
t.datetime "created_at" t.datetime 'created_at'
t.datetime "updated_at" t.datetime 'updated_at'
end end
add_index "post_tags", ["post_id"], name: "index_post_tags_on_post_id" add_index 'post_tags', ['post_id'], name: 'index_post_tags_on_post_id'
add_index "post_tags", ["tag_id"], name: "index_post_tags_on_tag_id" add_index 'post_tags', ['tag_id'], name: 'index_post_tags_on_tag_id'
create_table "posts", force: true do |t| create_table 'posts', force: true do |t|
t.string "title" t.string 'title'
t.text "body" t.text 'body'
t.integer "author_id" t.integer 'author_id'
t.datetime "created_at" t.datetime 'created_at'
t.datetime "updated_at" t.datetime 'updated_at'
end end
create_table "tags", force: true do |t| create_table 'tags', force: true do |t|
t.string "name" t.string 'name'
t.datetime "created_at" t.datetime 'created_at'
t.datetime "updated_at" t.datetime 'updated_at'
t.string "ancestry" t.string 'ancestry'
end end
add_index "tags", ["ancestry"], name: "index_tags_on_ancestry" add_index 'tags', ['ancestry'], name: 'index_tags_on_ancestry'
create_table "users", force: true do |t| create_table 'users', force: true do |t|
t.string "name" t.string 'name'
t.string "image_url" t.string 'image_url'
t.datetime "created_at" t.datetime 'created_at'
t.datetime "updated_at" t.datetime 'updated_at'
t.string "email", default: "", null: false t.string 'email', default: '', null: false
t.string "encrypted_password", default: "", null: false t.string 'encrypted_password', default: '', null: false
t.string "reset_password_token" t.string 'reset_password_token'
t.datetime "reset_password_sent_at" t.datetime 'reset_password_sent_at'
t.datetime "remember_created_at" t.datetime 'remember_created_at'
t.integer "sign_in_count", default: 0, null: false t.integer 'sign_in_count', default: 0, null: false
t.datetime "current_sign_in_at" t.datetime 'current_sign_in_at'
t.datetime "last_sign_in_at" t.datetime 'last_sign_in_at'
t.string "current_sign_in_ip" t.string 'current_sign_in_ip'
t.string "last_sign_in_ip" t.string 'last_sign_in_ip'
t.string "google_auth_token" t.string 'google_auth_token'
t.string "google_refresh_token" t.string 'google_refresh_token'
t.datetime "google_token_expires_at" t.datetime 'google_token_expires_at'
end end
add_index "users", ["email"], name: "index_users_on_email", unique: true add_index 'users', ['email'], name: 'index_users_on_email', unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true add_index 'users', ['reset_password_token'], name: 'index_users_on_reset_password_token', unique: true
end end
...@@ -6,7 +6,6 @@ ...@@ -6,7 +6,6 @@
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first) # Mayor.create(name: 'Emanuel', city: cities.first)
# Tag # Tag
_tag_tree = [ _tag_tree = [
...@@ -31,7 +30,7 @@ _tag_tree = [ ...@@ -31,7 +30,7 @@ _tag_tree = [
tags = [] tags = []
_tag_tree.each do |_parent, _child| _tag_tree.each do |_parent, _child|
puts "[Seed Tag] #{_parent} => #{_child}" Rails.logger.debug "[Seed Tag] #{_parent} => #{_child}"
parent = Tag.find_or_create_by(name: _parent) if _parent parent = Tag.find_or_create_by(name: _parent) if _parent
child = Tag.find_or_initialize_by(name: _child) child = Tag.find_or_initialize_by(name: _child)
child.parent = parent if _parent child.parent = parent if _parent
...@@ -39,28 +38,27 @@ _tag_tree.each do |_parent, _child| ...@@ -39,28 +38,27 @@ _tag_tree.each do |_parent, _child|
tags << child tags << child
end end
# User # User
User.find_or_create_by(name: '山田太郎') do |_u| User.find_or_create_by(name: '山田太郎') do |_u|
_u.email = "#{Devise.friendly_token[0,20]}@example.com" _u.email = "#{Devise.friendly_token[0, 20]}@example.com"
_u.password = Devise.friendly_token[0,20] _u.password = Devise.friendly_token[0, 20]
end end
User.find_or_create_by(name: '鈴木二郎') do |_u| User.find_or_create_by(name: '鈴木二郎') do |_u|
_u.email = "#{Devise.friendly_token[0,20]}@example.com" _u.email = "#{Devise.friendly_token[0, 20]}@example.com"
_u.password = Devise.friendly_token[0,20] _u.password = Devise.friendly_token[0, 20]
end end
User.find_or_create_by(name: '田中三郎') do |_u| User.find_or_create_by(name: '田中三郎') do |_u|
_u.email = "#{Devise.friendly_token[0,20]}@example.com" _u.email = "#{Devise.friendly_token[0, 20]}@example.com"
_u.password = Devise.friendly_token[0,20] _u.password = Devise.friendly_token[0, 20]
end end
# Post # Post
users = User.all users = User.all
Dir.glob(Rails.root.join('db', 'seeds').to_s + '/*').each do |file_name| Dir.glob(Rails.root.join('db', 'seeds').to_s + '/*').each do |file_name|
puts "[Post Tag] #{file_name}" Rails.logger.debug "[Post Tag] #{file_name}"
title = file_name.split('/').last title = file_name.split('/').last
post = Post.find_or_initialize_by(title: title) post = Post.find_or_initialize_by(title: title)
...@@ -69,4 +67,3 @@ Dir.glob(Rails.root.join('db', 'seeds').to_s + '/*').each do |file_name| ...@@ -69,4 +67,3 @@ Dir.glob(Rails.root.join('db', 'seeds').to_s + '/*').each do |file_name|
post.tags = [tags.sample, tags.sample] post.tags = [tags.sample, tags.sample]
post.save! post.save!
end end
...@@ -3,29 +3,29 @@ require 'spec_helper' ...@@ -3,29 +3,29 @@ require 'spec_helper'
describe HomeController do describe HomeController do
describe "GET 'top'" do describe "GET 'top'" do
it "should be successful" do it 'should be successful' do
get :top get :top
expect(response).to be_success expect(response).to be_success
expect(response.code).to eq("200") expect(response.code).to eq('200')
end end
end end
describe 'Login' do describe 'Login' do
before (:each) do before(:each) do
@user = FactoryGirl.create(:login_user_1) @user = FactoryGirl.create(:login_user_1)
sign_in @user sign_in @user
end end
describe "GET 'top'" do describe "GET 'top'" do
it "should be successful" do it 'should be successful' do
get :top get :top
expect(subject).to redirect_to controller: 'posts', expect(subject).to redirect_to controller: 'posts',
action: 'index' action: 'index'
end end
it "should find the right user" do it 'should find the right user' do
get :top get :top
expect(assigns(:current_user)).to eq(@user) expect(assigns(:current_user)).to eq(@user)
end end
......
FactoryGirl.define do FactoryGirl.define do
factory :alice, class: User do factory :alice, class: User do
name 'Alice' name 'Alice'
email "alice@mail.com" email 'alice@mail.com'
password Devise.friendly_token[0,20] password Devise.friendly_token[0, 20]
google_token_expires_at Time.now + 30.minutes google_token_expires_at Time.now + 30.minutes
end end
factory :bob, class: User do factory :bob, class: User do
name 'Bob' name 'Bob'
email "bob@mail.com" email 'bob@mail.com'
password Devise.friendly_token[0,20] password Devise.friendly_token[0, 20]
google_token_expires_at Time.now - 1.hour google_token_expires_at Time.now - 1.hour
end end
......
...@@ -24,102 +24,99 @@ describe User do ...@@ -24,102 +24,99 @@ describe User do
describe 'validation' do describe 'validation' do
before(:each) do before(:each) do
@attr = { @attr = {
:name => "Example User", name: 'Example User',
:email => "user@example.com", email: 'user@example.com',
:password => "changeme", password: 'changeme',
:password_confirmation => "changeme" password_confirmation: 'changeme'
} }
end end
it "should create a new instance given a valid attribute" do it 'should create a new instance given a valid attribute' do
User.create!(@attr) User.create!(@attr)
end end
it "should require an email address" do it 'should require an email address' do
no_email_user = User.new(@attr.merge(:email => "")) no_email_user = User.new(@attr.merge(email: ''))
no_email_user.should_not be_valid no_email_user.should_not be_valid
end end
it "should accept valid email addresses" do it 'should accept valid email addresses' do
addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp] addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
addresses.each do |address| addresses.each do |address|
valid_email_user = User.new(@attr.merge(:email => address)) valid_email_user = User.new(@attr.merge(email: address))
valid_email_user.should be_valid valid_email_user.should be_valid
end end
end end
it "should reject invalid email addresses" do it 'should reject invalid email addresses' do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.] addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
addresses.each do |address| addresses.each do |address|
invalid_email_user = User.new(@attr.merge(:email => address)) invalid_email_user = User.new(@attr.merge(email: address))
invalid_email_user.should_not be_valid invalid_email_user.should_not be_valid
end end
end end
it "should reject duplicate email addresses" do it 'should reject duplicate email addresses' do
User.create!(@attr) User.create!(@attr)
user_with_duplicate_email = User.new(@attr) user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid user_with_duplicate_email.should_not be_valid
end end
it "should reject email addresses identical up to case" do it 'should reject email addresses identical up to case' do
upcased_email = @attr[:email].upcase upcased_email = @attr[:email].upcase
User.create!(@attr.merge(:email => upcased_email)) User.create!(@attr.merge(email: upcased_email))
user_with_duplicate_email = User.new(@attr) user_with_duplicate_email = User.new(@attr)
user_with_duplicate_email.should_not be_valid user_with_duplicate_email.should_not be_valid
end end
describe "passwords" do describe 'passwords' do
before(:each) do before(:each) do
@user = User.new(@attr) @user = User.new(@attr)
end end
it "should have a password attribute" do it 'should have a password attribute' do
@user.should respond_to(:password) @user.should respond_to(:password)
end end
it "should have a password confirmation attribute" do it 'should have a password confirmation attribute' do
@user.should respond_to(:password_confirmation) @user.should respond_to(:password_confirmation)
end end
end end
describe "password validations" do describe 'password validations' do
it "should require a password" do it 'should require a password' do
User.new(@attr.merge(:password => "", :password_confirmation => "")). User.new(@attr.merge(password: '', password_confirmation: '')).should_not be_valid
should_not be_valid
end end
it "should require a matching password confirmation" do it 'should require a matching password confirmation' do
User.new(@attr.merge(:password_confirmation => "invalid")). User.new(@attr.merge(password_confirmation: 'invalid')).should_not be_valid
should_not be_valid
end end
it "should reject short passwords" do it 'should reject short passwords' do
short = "a" * 5 short = 'a' * 5
hash = @attr.merge(:password => short, :password_confirmation => short) hash = @attr.merge(password: short, password_confirmation: short)
User.new(hash).should_not be_valid User.new(hash).should_not be_valid
end end
end end
describe "password encryption" do describe 'password encryption' do
before(:each) do before(:each) do
@user = User.create!(@attr) @user = User.create!(@attr)
end end
it "should have an encrypted password attribute" do it 'should have an encrypted password attribute' do
@user.should respond_to(:encrypted_password) @user.should respond_to(:encrypted_password)
end end
it "should set the encrypted password attribute" do it 'should set the encrypted password attribute' do
@user.encrypted_password.should_not be_blank @user.encrypted_password.should_not be_blank
end end
end end
end end
end end
# coveralls # coveralls
require 'coveralls' require 'coveralls'
Coveralls.wear! Coveralls.wear!
# This file is copied to spec/ when you run 'rails generate rspec:install' # This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test' ENV['RAILS_ENV'] ||= 'test'
require File.expand_path("../../config/environment", __FILE__) require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails' require 'rspec/rails'
require 'rspec/autorun' require 'rspec/autorun'
# require 'email_spec' # require 'email_spec'
...@@ -14,7 +12,7 @@ require 'factory_girl' ...@@ -14,7 +12,7 @@ require 'factory_girl'
# Requires supporting ruby files with custom matchers and macros, etc, # Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories. # in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migrations before tests are run. # Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line. # If you are not using ActiveRecord, you can remove this line.
...@@ -46,16 +44,14 @@ RSpec.configure do |config| ...@@ -46,16 +44,14 @@ RSpec.configure do |config|
# order dependency and want to debug it, you can fix the order by providing # order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run. # the seed, which is printed after each run.
# --seed 1234 # --seed 1234
config.order = "random" config.order = 'random'
config.include FactoryGirl::Syntax::Methods config.include FactoryGirl::Syntax::Methods
# config.include(EmailSpec::Helpers) # config.include(EmailSpec::Helpers)
# config.include(EmailSpec::Matchers) # config.include(EmailSpec::Matchers)
config.before(:all) do config.before(:all) do
FactoryGirl.reload FactoryGirl.reload
end end
end end
RSpec.configure do |config| RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller config.include Devise::TestHelpers, type: :controller
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment