简体   繁体   English

没有运行before_save

[英]Not running before_save

I have a model with before_save :autofill_country_code which will fill missing values. 我有一个具有before_save :autofill_country_code的模型before_save :autofill_country_code ,它将填充缺失的值。 However, when I run my rspec test, it doesn't seem to run the before_save. 但是,当我运行rspec测试时,它似乎没有运行before_save。

I pried my test open and saving did not update the attributes. 我将测试撬开,保存并没有更新属性。

How do I work around this? 我该如何解决?

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

The following is my autofill 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

Do you have validation set up for country_code ? 您是否为country_code设置了验证? Hooks are performed in that order: 挂钩按以下顺序执行:

before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save

So if model is invalid, before_save hook will not be executed. 因此,如果模型无效,将不执行before_save挂钩。 Try before_validation :autofill_country_code instead. 请尝试before_validation :autofill_country_code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM