2011-04-15 79 views
1

我有一個基於redis的新聞訂閱源,當某些事件發生時,通過回調獲取項目。例如,當用戶在一本書上留言時,它會被插入到本書讀者的新聞中。使用lambda測試rails中的回調?

class Note < ActiveRecord::Base 
    after_save do |note| 
    notify_the note.book.readers 
    end 

... 
end 

現在這很好,我99%肯定它的工作原理,因爲我可以看我的飼料,看看那裏的筆記。我的問題是用最新的rspec-rails在Rails 3上測試它。

出於某種原因,這個通行證:

spec/models/note_spec.rb 
describe "note creation" do 
    it "should notify the readers of the book the note is on" do 
    @user.feed.count.should == 0 
    @note.save! 
    @user.feed.count.should == 1 
    end 
end 

但這並不:

spec/models/note_spec.rb 
describe "note creation" do 
    it "should notify the readers of the book the note is on" do 
    lambda do 
     @note.save! 
    end.should change(@user.feed, :count).by(1) 
    end 
end 

,我想不出有什麼區別?

+0

我唯一能想到的就是`@ note.save!`拋出了一個異常,並且它不會因爲它在lambda中被隔離而冒泡。但是,如果第二次測試中的「@ note」與第一次測試中的「完全相同」,那不太可能。 – 2011-04-15 19:22:40

+0

是的,他們肯定是一樣的。 – 2011-04-16 01:25:34

回答

0

爲了使用lambda和測試進行更改,需要使用大括號{} - 不支持do/end語法(尚)。