Skip to content

Instantly share code, notes, and snippets.

@doolin
Created June 6, 2011 01:14
Show Gist options
  • Save doolin/1009614 to your computer and use it in GitHub Desktop.
Save doolin/1009614 to your computer and use it in GitHub Desktop.
person_spec.rb
class Person < ActiveRecord::Base
validates :first_name, :presence => true
validates :last_name, :presence => true
end
require 'spec_helper'
describe Person do
# Yes, yes, this could be build from a
# Factory...
before(:each) do
@valid_attributes = {
:first_name => "Joe",
:last_name => "Bloggs"
}
end
it "creates a valid Person given valid attributes" do
lambda {
Person.create(@valid_attributes)
# Alternate method...
# }.should change(Person, :count).from(0).to(1)
}.should change(Person, :count).by(1)
end
# Syntax examples.
it "should save the first name" do
p = Person.create({:first_name => "John", :last_name => "Smith"})
p.first_name.should == "John"
end
it "should save the last name" do
p = Person.create({:first_name => "John", :last_name => "Smith"})
p.last_name.should == "Smith"
end
# The following two are dangerous. If only the
# invalid part is checked, the test produces a
# false positive. A better way to do this would be
# use @valid_attributes, then override the attribute
# being tested. Try it yourself!
it "must have a first name" do
lambda {
#Person.create({:first_name => ''})
Person.create({:first_name => '', :last_name => "Smith"})
}.should_not change(Person, :count)
end
it "must have a last name" do
lambda {
#Person.create({:last_name => ''})
Person.create({:first_name => "John", :last_name => ''})
}.should_not change(Person, :count)
end
# Same issue as above, try it yourself.
it "must have a first name" do
#p = Person.new({:first_name => ''}) # creates a false positive
p = Person.new({:first_name => '', :last_name => "Smith"})
p.should_not be_valid
end
it "must have a last name" do
p = Person.new({:first_name => 'John', :last_name => ''})
p.should_not be_valid
end
end
@doolin
Copy link
Author

doolin commented Jun 6, 2011

Reference validation tests from Wolf Arnold's Efficient Test Driven Rails Development class summer 2010.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment