2014-08-29 24 views
1

我有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) } ?什麼是最好的方法?

回答

1

我更喜歡第一個選項。假設你的另一個模型有一些驗證,before_save或before_create回調不能保存數據到表的情況?

通過使用shared_examples_for您可以輕鬆地分發所需的片規格的用於在這種模型類中使用Uuidable關注進行測試。另一方面,如果您使用第二種方法,它將僅限於一個模型:DummyClass,並且可能每次都傳遞其規格,而不管使用Uuidable模塊的模型中的驗證或其他回調失敗。

你的做法是正確的。只需在模型的規格中使用it_behaves_like "Uuidable"即可,這些規格使用了這個問題並讓它們獨立運行。