模型在规格之前运行

我有以下spec文件:

describe 'before_save autofill country code' do it "should autofill country code" do empty_country_code = nil @store = Factory.build(:store, :country_code => empty_country_code) expect{ @store.save }.to change { @store.country_code }.from(nil).to('1') end end 

工厂定义如下:

 Factory.define :store do |store| store.city "New York" store.country_code "81" end 

我的模型有以下几行:

 before_save :autofill_country_code 

哪里

 def autofill_country_code unless self.country_code.present? country = GeoCache.geocode(self.city).country_code country_code = IsoCountryCodes.find(country).calling self.country_code = country_code.tr('+', '') end end 

据我所知,当我运行一个spec文件时,它应该首先从规范运行。 然而,在撬开代码一段时间后,我意识到模型首先加载。 它用country_code 81填充country_code ,因此无法运行autofill_country_code

然后,它转到spec文件并将country_code设置为nil 。 在我写这篇文章时expect ,我的规范的expect线可能是错误的。 我收到一条错误说明:

 result should have been changed to "1", but is now nil 

有任何想法吗?