2013-01-14 50 views
0

我有這樣的問題。我的測試檢查Observer是否調用,但不執行它。 我的文件:Rails 3.2.9。使用RSpec測試觀察者(遇到should_receive)


todo_observer.rb:

class TodoObserver < ActiveRecord::Observer  
    def after_create(todo) 
    todo.add_log('creating') 
    end  
end 

todo.rb:

class Todo < ActiveRecord::Base 
    attr_accessible :content, :done, :order 

    validates :content, :presence => true, 
      :length => {:minimum => 2} 

    def add_log(event) 
    Logdata.start_logging(self.content, event) 
    end 
end 

logdata.rb

class Logdata < ActiveRecord::Base 
    attr_accessible :modification, :event 

    def self.start_logging(content, event) 
    Logdata.create!(:modification => content, :event => event) 
    end 
end 

todo_observer_spec.rb:

require 'spec_helper' 

describe TodoObserver do 

    before(:each) do 
    @attr = { :modification => "Example", :event => 'Event' } 
    @attr_todo = { :content => "Example", :done => :false } 
    end 

    describe 'after_create' do 
    it "should create log about creating task" do 
     count_log = Logdata.all.size 
     todo = Todo.new(@attr_todo) 
     todo.should_receive(:add_log).with('creating') 
     todo.save! 
     (Logdata.all.size).should eq(count_log + 1) 
    end 
    end 

end 

當我運行測試,我得到這樣的錯誤

Failure/Error: (Logdata.all.size).should eq(count_log + 1)

expected: 1 
     got: 0 

它的意思是,觀察員呼籲,但Logdata不會創建實例。當我評論的字符串(查看通話)

todo.should_receive(:add_log).with('creating')

我的測試是successful.And因此其成功的時候我的註釋字符串(Logdata.all.size).should eq(count_log + 1)並取消以前的字符串。 功能should_receive創建類的實例Logdata

+0

請注意,由於存在安全漏洞,您應該立即更新到rails 3.2.11:http://weblog.rubyonrails.org/2013/1/8/Rails-3-2-11 -3-1-10-3-0-19-and-2-3-15-have-been-released/ –

回答

1

should_receive阻止實際的方法被調用。

您應該創建兩個單獨的測試。一個檢查是否將日誌添加到待辦事項中,另一個檢查日誌是否已創建。

describe 'after_create' do 
    it "should add a log to the todo" do 
    todo = Todo.new(@attr_todo) 
    todo.should_receive(:add_log).with('creating') 
    todo.save! 
    end 

    it "should create a new logdata" do 
    todo = Todo.new(@attr_todo) 
    expect { 
     todo.save! 
    }.to change {Logdata.count}.by(1) 
    end 
end 
+0

謝謝Daniel,你說得對。 – Boko