この単純な例では、DataMapper のbefore :save
コールバック (別名フック) を使用して をインクリメントしますcallback_count
。callback_count は 0 に初期化されており、コールバックによって 1 に設定する必要があります。
このコールバックは、次の方法で TestObject が作成されたときに呼び出されます。
TestObject.create()
ただし、次の方法で FactoryGirl によって作成された場合、コールバックはスキップされます。
FactoryGirl.create(:test_object)
理由はありますか?[注: ruby 1.9.3、factory_girl 4.2.0、data_mapper 1.2.0 を実行しています]
完全な詳細は次のとおりです...
DataMapper モデル
# file: models/test_model.rb
class TestModel
include DataMapper::Resource
property :id, Serial
property :callback_count, Integer, :default => 0
before :save do
self.callback_count += 1
end
end
FactoryGirl宣言
# file: spec/factories.rb
FactoryGirl.define do
factory :test_model do
end
end
RSpec テスト
# file: spec/models/test_model_spec.rb
require 'spec_helper'
describe "TestModel Model" do
it 'calls before :save using TestModel.create' do
test_model = TestModel.create
test_model.callback_count.should == 1
end
it 'fails to call before :save using FactoryGirl.create' do
test_model = FactoryGirl.create(:test_model)
test_model.callback_count.should == 1
end
end
テスト結果
Failures:
1) TestModel Model fails to call before :save using FactoryGirl.create
Failure/Error: test_model.callback_count.should == 1
expected: 1
got: 0 (using ==)
# ./spec/models/test_model_spec.rb:10:in `block (2 levels) in <top (required)>'
Finished in 0.00534 seconds
2 examples, 1 failure