0

我有这样的问题。我的测试检查 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

日志数据.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).should eq(count_log + 1)

   expected: 1
        got: 0

它的意思是,那个观察者调用了,但没有创建Logdata的实例。当我评论字符串时(检查电话)

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

我的测试是成功的。因此,当我评论字符串(Logdata.all.size).should eq(count_log + 1)并取消评论前一个字符串时它的成功。函数should_receive如何创建 Logdata 类的实例

4

1 回答 1

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
于 2013-01-14T17:55:01.177 回答