Rails 3.2.9。使用RSpec测试观察者(使用should_receive时遇到问题)

时间:2013-01-14 14:42:29

标签: ruby ruby-on-rails-3 rspec

我有这样的问题。我的测试检查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).should eq(count_log + 1)

   expected: 1
        got: 0

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

  

todo.should_receive(:add_log)。随着(&#39;创建&#39)

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

1 个答案:

答案 0 :(得分: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