我有AR模型关注Uuidable,看起来像这样:Rspec在describe_class或DummyClass中测试AR模型问题?
module Uuidable
extend ActiveSupport::Concern
included do
before_create :generate_uuid
end
protected
def generate_uuid
self.uuid = #some code
end
end
到目前为止,我已经写了shared_examples_for Uuidable
,看起来像这样:
shared_examples_for Uuidable do
let(:model) { FactoryGirl.build(described_class) }
it { expect(model).to callback(:generate_uuid).before(:create) }
describe '#generate_uuid' do
it { expect{model.save}.to change {model.uuid} }
it 'should not generate same uuid' do
allow(SecureRandom).to receive(:uuid).and_return("c640f32c-e21b-44ea-913e-7041fdb6de85", "c640f32c-e21b-44ea-913e-7041fdb6de85", "e93f0130-3a81-406f-8871-609d89ae0850")
model.save
expect(FactoryGirl.create(described_class).uuid).not_to eq(model.uuid)
end
context 'generated uuid field' do
before(:each) { model.save }
it { expect(model.uuid).to be_kind_of(String) }
it { expect(model.uuid).to match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}
end
end
end
所以...我想知道是在每个Uuidable
模型中测试#generate_uuid
方法的行为是否正确?
class DummyClass < ActiveRecord::Base
创建测试
Uuidable
关注和
shared_examples
第二个选项,你认为什么只留下it { expect(model).to callback(:generate_uuid).before(:create) }
?什么是最好的方法?