私はそのような問題を抱えています。私のテストでは、オブザーバーが呼び出したかどうかを確認しますが、実行はしません。私のファイル:
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).with('作成中')
私のテストは成功しました。それに応じて、文字列(Logdata.all.size).should eq(count_log + 1)
にコメントを付けて前の文字列のコメントを外すと、成功しました。関数should_receiveは、クラスLogdataのインスタンスをどのように作成しますか?