Created
February 2, 2009 17:30
-
-
Save raul/56996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# class to test | |
require 'rubygems' | |
require 'active_record' | |
class Post < ActiveRecord::Base | |
validates_presence_of :title | |
before_save :create_slug | |
private | |
def create_slug | |
self.slug ||= self.title.gsub(' ','-').downcase | |
end | |
end | |
# needed AR testing environment: I would not mock the entire connection, columns calls, etc, | |
# If that's your choice see: http://blog.jayfields.com/2006/12/rails-activerecord-unit-testing.html | |
require 'sqlite3' | |
ActiveRecord::Base.establish_connection( | |
:adapter => 'sqlite3', | |
:database => 'test.db' | |
) | |
ActiveRecord::Schema.define do | |
create_table :posts, :force => true do |t| | |
t.column :title, :string | |
t.column :slug, :string | |
end | |
end | |
# the tests properly said: | |
require 'test/unit' | |
require 'mocha' | |
class PostTest < Test::Unit::TestCase | |
def setup | |
@post = Post.new :title => "First post" | |
end | |
def test_slug_generated_on_creation | |
@post.expects(:create).returns true # expects(:save) doesn't execute before_save callback, | |
# so we need to mock/stub the underlying create/update call | |
@post.save | |
assert_equal 'first-post', @post.slug | |
end | |
def test_slug_doesnt_change_on_updates | |
@post.save | |
@post.title = 'another title' | |
@post.expects(:update).returns true # expects(:save) doesn't execute before_save callback, | |
# so we need to mock/stub the underlying create/update call | |
@post.save | |
assert_equal 'first-post', @post.slug | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment