Skip to content

Instantly share code, notes, and snippets.

@HoyaBoya
Last active December 19, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoyaBoya/5868987 to your computer and use it in GitHub Desktop.
Save HoyaBoya/5868987 to your computer and use it in GitHub Desktop.
I'm trying to understand Active Record again....
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :first_name
t.string :last_name
t.timestamps
end
add_index :users, :email, unique: true
end
end
# http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html
class User < ActiveRecord::Base
validates :first_name, presence: true
validates :last_name, presence: true
validates :email, presence: true, uniqueness: true, format:{ with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i}
end
require 'test_helper'
#http://guides.rubyonrails.org/active_record_querying.html
class UserTest < ActiveSupport::TestCase
def setup
@user_fields = {first_name: 'Chris', last_name: 'S', email: 'cs@foo.com'}
end
test "it should validate with all fields present" do
user = User.new(@user_fields)
assert user.valid?, 'Expect user to be valid'
end
test "it should require email to be unique" do
user = User.new(@user_fields)
user.save
assert_equal 1, User.count
user = User.new(@user_fields.merge(first_name: 'John', last_name: 'Smith'))
assert !user.valid?, 'Expect second user to be invalid'
assert_raises(ActiveRecord::RecordInvalid) do
user.save!
end
assert_equal 1, User.count
end
# this really isn't a good test, but i want to make sure i understand Active Record finders still
test "it should find by last_name" do
User.new(@user_fields).save!
assert 1, User.count
# find with new find_by
user = User.find_by first_name: 'Chris'
assert user.instance_of?(User), 'Expect user to be of type User'
assert_equal 'cs@foo.com', user.email, 'Expect email to be cs@foo.com'
# find with where
users = User.where('first_name = ?', 'Chris').order(:first_name)
assert users, 'Expect a users array'
assert_equal 1, users.size, 'Expect only 1 user'
assert_equal 'cs@foo.com', users.first.email, 'Expect email to be cs@foo.com'
end
# meta-test that all user fields must be present
[:first_name, :last_name, :email].each do |field|
test "it should require #{field} to be present" do
@user_fields.delete(field)
user = User.new(@user_fields)
assert !user.valid?, 'Expect user to be invalid'
assert user.errors[field], "Expect #{field} to have validation errors"
end
end
test "it should require a valid email" do
user = User.new(@user_fields)
user.email = 'i am not an email'
assert !user.valid?, 'Expect user to be invalid'
assert user.errors[:email], 'Expect email to have validation errors'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment