2011-09-02 115 views
5

after_create钩我的代码在我的模型(ROR 3.0.x的)那或多或少是这样的:测试使用RSpec

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的宝石进行测试。 问题是我无法测试通知方法:如果我直接测试它,我不能,因为它是受保护的,如果我创建一条消息并设置期望它不起作用,因为显然即使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 => "[email protected]") 
     Notifier.should_receive(:message_from_portfolio) 
     message.save 
    end 
end 

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

回答

3

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

+0

但是使用了'u.messages.build'。这不是你的建议吗? – lulalala

0

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

你可以设定一个期望调试目的:

message.should_receive(:after_create) 

或许visible?返回false?要检查,你可以使用一个负面的预期:

Notifier.should_not_receive(:invisible_message_from_portfolio)