Skip to content

Instantly share code, notes, and snippets.

@ppdeassis
Last active December 17, 2015 08:09
Show Gist options
  • Save ppdeassis/5578406 to your computer and use it in GitHub Desktop.
Save ppdeassis/5578406 to your computer and use it in GitHub Desktop.
Template for a Model spec
require 'spec_helper'
describe Person do
# NOTE: build, create and attributes_for are FactoryGirl methods
# You should include this line in spec_helper to make them available
# without FactoryGirl. (prefix):
# ---
# Rspec.configure do |config|
# ...
# => config.include FactoryGirl::Syntax::Methods
# ...
# end
# ---
let(:person) { build(:person) }
context 'factories' do
it 'valid' do
expect(build(:person)).to be_valid
end
end
context 'callbacks' do
it 'age is updated after save' do
birth_date = Date.new(1987, 6, 25)
person.birth_date = birth_date
person.save!
# calculating age correctly
now = Date.today
age = now.year - 1987
unless now.month > birth_date.month ||
(now.month == birth_date.month && now.day >= birth_date.day)
age -= 1
end
expect(person.age).to eq(age)
end
end
context 'associations' do
context 'belongs to' do
it 'city' do
expect(person.city).to be_a_kind_of(City)
end
end
# Exercise: has_many associations
end
context 'attributes' do
# Rails < 4 only
context 'accessible' do
it 'name' do
expect(Person.accessible_attributes).to include(:name)
end
end
# same thing, with implicit spec
context 'accessible' do
subject { Person.accessible_attributes }
it { should include(:name) }
end
context 'nested' do
# belongs_to or has_one example
it 'address' do
# making sure it's empty
person.address = nil
attrs = attributes_for(:address)
expect do
person.update_attributes(address_attributes: attrs)
end.to change(Address, :count).by(1)
end
# has_many example
context 'emails' do
it 'valid attrs' do
# making sure it's empty
person.emails = []
attrs = [attributes_for(:email)]
expect do
person.update_attributes(emails_attributes: attrs)
end.to change(Email, :count).by(attrs.size)
end
it 'rejects if address is blank' do
attrs = [attributes_for(:email, address: nil)]
expect do
person.update_attributes(emails_attributes: attrs)
end.not_to change(Email, :count)
end
it 'allows destroy' do
email = create(:email)
person.emails << email
expect do
person.update_attributes(emails_attributes: [{id: email.id, _destroy: true}]
end.to change(Email, :count).by(-1)
end
end
end
end
context 'validations' do
context 'name' do
it 'presence' do
person.name = nil
expect(person).to have_at_least(1).errors_on(:name)
end
it 'uniqueness' do
person.save!
dupe = person.dup
expect(dupe).to have_at_least(1).errors_on(:name)
end
end
context 'city' do
it 'presence' do
person.city = nil
expect(person).to have_at_least(1).errors_on(:city)
end
end
end
context 'scopes' do
# TODO
end
context 'methods' do
# TODO
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment