2011-09-02 202 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)