[英]Not running before_save
我有一个具有before_save :autofill_country_code
的模型before_save :autofill_country_code
,它将填充缺失的值。 但是,当我运行rspec测试时,它似乎没有运行before_save。
我将测试撬开,保存并没有更新属性。
我该如何解决?
it "should autofill country code" do
empty_country_code = ''
@store = Factory.build(:store, :country_code => empty_country_code)
expect{ @store.save }.to change{ @store.country_code }.from('').to(1)
end
以下是我的自动填充代码:
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
您是否为country_code
设置了验证? 挂钩按以下顺序执行:
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
因此,如果模型无效,将不执行before_save挂钩。 请尝试before_validation :autofill_country_code
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.