Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing after_create hooks with rspec

I have code in my model (RoR 3.0.x) that is more or less like this:

class Message

    after_create :notify

    protected

    def notify
        if visible?
            Notifier.message_from_portfolio( user, self ).deliver
        else
            Notifier.invisible_message_from_portfolio( user, self ).deliver
        end
    end

end

And I'm using the latest rspec gem to test it. The problem is that I'm not able to test the notify method: if I test it directly I can't because it's protected, if I create a message and set expectations it doesn't work because apparently even though rspec runs the notify metod I'm not able to catch the calls in time.

My spec is:

describe :notification do
    it "should send the whole message by email when visible" do
        u = Factory.create( :user, :account_type => 1 )
        message = u.messages.build( :body => "Whatever", :author => "Nobody", :email => "[email protected]" )
        Notifier.should_receive( :message_from_portfolio )
        message.save
    end
end

The object Notifier never receives message_from_portfolio. What am I doing wrong? Suggestions?

like image 907
ngw Avatar asked Sep 02 '11 14:09

ngw


1 Answers

Factory.create has already saved message, so it is not being created, just saved. Substitute it with Factory.build and all should be fine.

like image 190
Serabe Avatar answered Nov 15 '22 09:11

Serabe