开发者

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 meto开发者_如何学Cd 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 => "test@example.com" )
        Notifier.should_receive( :message_from_portfolio )
        message.save
    end
end

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


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


Are you sure the callback is being reached? after_create doesn't get executed if the instance is invalid.

You could set an expectation for debugging purposes:

message.should_receive(:after_create)

Or maybe visible? returns false? To check for that you could use a negative expectation:

Notifier.should_not_receive(:invisible_message_from_portfolio)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜