Skip to content

Instantly share code, notes, and snippets.

@pdswan
Created June 1, 2012 18:08
Show Gist options
  • Save pdswan/2854097 to your computer and use it in GitHub Desktop.
Save pdswan/2854097 to your computer and use it in GitHub Desktop.
Testing Classes for Active Record Callbacks
require 'test/unit'
require 'mocha'
# assumes MailingListUpdater is defined / exposed at the top level. this is not the case
# for the code in this gist.
class MailingListUpdaterTest < Test::Unit::TestCase
test "#update_mailing_list calls enqueue_for_mailing_list_update when a user is present" do
user = mock('User', :enqueue_for_mailing_list_update => true)
record = stub('Record')
record.stubs(:user).returns(user)
MailingListUpdater.new.update_mailing_list(record)
end
test "#update_mailing_list fails silently if a user is not present" do
record = stub('Record')
record.stubs(:user).returns(nil)
assert_nothing_raised do
MailingListUpdater.new.update_mailing_list(record)
end
end
...
end
class Model
class MailingListUpdater
def initialize(user_proc = lambda { |record| record.user })
@user_proc = user_proc
end
def user(record)
@user_proc.call(record)
end
def update_mailing_list(record)
return unless user(record)
user(record).enqueue_for_mailing_list_update
end
alias_method :after_create, :update_mailing_list
...
end
after_create MailingListUpdater.new
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment