Writing a spec for an observer that launches an email program

I am writing a simple comment observer that launches an email program whenever a new comment is created. All relevant code is in this context: https://gist.github.com/c3234352b3c4776ce132

Note that the specifications for Notificationpass, but the specifications for CommentObserverfail because it Notification.new_commentreturns nil. I found that instead I can get the missing spec:

describe CommentObserver do
  it "sends a notification mail after a new comment is created" do
    Factory(:comment)
    ActionMailer::Base.deliveries.should_not be_empty
  end
end

This is not ideal, however, because it checks the behavior of the mail program in the observer specification, when all I really want to know is that it starts the mail program correctly. Why nildoes the mailer return to the original version of the specification? What is the best approach to define this type of functionality? I use Rails 3 and RSpec 2 (and Factory Girl, if that matters).

+3
source share
1 answer

for context:

class CommentObserver < ActiveRecord::Observer
  def after_create(comment)
    Notification.new_comment(comment).deliver
  end
end

# spec
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

In this case, you want to check what is called in the notification deliver, so that when waiting is expected. The rest of the specification code is for setting the wait and starting it. Try it like this:

describe CommentObserver do
  it "sends a notification mail after a new comment is created" do
    @comment = Factory.build(:comment)
    notification = mock(Notification)
    notification.should_receive(:deliver)
    Notification.stub(:new_comment).with(@comment).and_return(notification)
    @comment.save
  end
end

?

, , - .and_return() , should_receive nil.

+8

Source: https://habr.com/ru/post/1792610/


All Articles