【问题标题】:Testing after_create hooks with rspec使用 rspec 测试 after_create 钩子
【发布时间】:2011-09-02 14:20:57
【问题描述】:

我的模型(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 来测试它。 问题是我无法测试 notify 方法:如果我直接测试它,我不能因为它受到保护,如果我创建一条消息并设置期望它不起作用,因为显然即使 rspec 运行 notify 方法我无法及时接听电话。

我的规格是:

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。我究竟做错了什么?有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    Factory.create 已经保存了消息,所以它没有被创建,只是被保存了。用Factory.build 代替它,一切都会好起来的。

    【讨论】:

    • 但是使用了u.messages.build。这不是你建议的吗?
    【解决方案2】:

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

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

    message.should_receive(:after_create)
    

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

    Notifier.should_not_receive(:invisible_message_from_portfolio)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      相关资源
      最近更新 更多