6

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 => "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?

4

2 回答 2

3

Factory.create已经保存了消息,所以它没有被创建,只是保存。用它代替它,Factory.build一切都应该没问题。

于 2011-09-02T20:09:22.393 回答
1

您确定正在达到回调吗?after_create如果实例无效,则不会执行。

您可以为调试目的设置期望:

message.should_receive(:after_create)

或者可能visible?返回false?要检查这一点,您可以使用负期望:

Notifier.should_not_receive(:invisible_message_from_portfolio)
于 2011-09-02T16:05:45.920 回答