使用rspec测试after_create挂钩

时间:2011-09-02 14:20:58

标签: ruby-on-rails-3 rspec rspec2 rspec-rails

我的模型(RoR 3.0.x)中的代码或多或少是这样的:

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

我正在使用最新的rspec gem来测试它。 问题是我无法测试通知方法:如果我直接测试它我不能因为它受到保护,如果我创建一条消息并设置期望它不起作用,因为很明显即使rspec运行通知metod我无法及时接听电话。

我的规格是:

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

对象通知程序永远不会收到message_from_portfolio。我究竟做错了什么?建议?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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

message.should_receive(:after_create)

或者visible?可能会返回false?要检查你是否可以使用负面预期:

Notifier.should_not_receive(:invisible_message_from_portfolio)