我有这样的问题。我的测试检查Observer是否调用,但不执行它。我的文件:
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
当我运行测试时,我得到这样的错误
失败/错误:(Logdata.all.size)。应该eq(count_log + 1)
expected: 1 got: 0
它的平均值,观察者调用,但不创建Logdata的实例。当我注释字符串(检查调用)
todo.should_receive (add_log);(创造)
我的测试成功了。相应地,当我注释字符串(Logdata.all.size).should eq(count_log + 1)
并取消注释前一个字符串时,它的成功。函数应该如何接收来创建类Logdata的实例?
should_receive
阻止实际的方法被调用。
您应该创建两个独立的测试。一个检查日志是否已添加到todo,另一个检查日志是否已创建。
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