secret
Created

  • Download Gist
application.rb
Ruby
1 2 3
# ...
config.active_record.observers = :comment_observer
# ...
comment_observer.rb
Ruby
1 2 3 4 5
class CommentObserver < ActiveRecord::Observer
def after_create(comment)
Notification.new_comment(comment).deliver
end
end
comment_observer_spec.rb
Ruby
1 2 3 4 5 6 7 8 9
require 'spec_helper'
 
describe CommentObserver do
it "sends a notification mail after a new comment is created" do
@comment = Factory.build(:comment)
Notification.should_receive(:new_comment).with(@comment)
@comment.save
end
end
notification.rb
Ruby
1 2 3 4 5 6
class Notification < ActionMailer::Base
def new_comment(comment)
@comment = comment
mail(:to => ENV["ADMIN_EMAIL"], :from => ENV["ADMIN_EMAIL"], :subject => "New comment from #{@comment.name} on #{@comment.post.title}")
end
end
notification_spec.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
require "spec_helper"
 
describe Notification do
describe "#new_comment" do
before(:each) do
ENV["ADMIN_EMAIL"] = 'admin@example.com'
@comment = Factory(:comment)
@email = Notification.new_comment(@comment).deliver
end
 
it "queues a message for new comments" do
ActionMailer::Base.deliveries.should_not be_empty
end
 
it "sends email to and from the admin" do
@email.to.should include(ENV["ADMIN_EMAIL"])
@email.from.should include(ENV["ADMIN_EMAIL"])
end
end
end
rspec_output.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Notification
#new_comment
queues a message for new comments
sends email to and from the admin
 
CommentObserver
sends a notification mail after a new comment is created (FAILED - 1)
 
 
 
 
Failures:
 
1) CommentObserver sends a notification mail after a new comment is created
Failure/Error: @comment.save
NoMethodError:
undefined method `deliver' for nil:NilClass
# ./app/models/comment_observer.rb:3:in `after_create'
# ./spec/models/comment_observer_spec.rb:7:in `block (2 levels) in <top (required)>'

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.