这个简单的例子使用 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]
详细信息如下...
数据映射器模型
# 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