Marco Lau Marco Lau - 5 months ago 14
Ruby Question

Not running before_save

I have a model with

before_save :autofill_country_code
which will fill missing values. However, when I run my rspec test, it doesn't seem to run the 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

Answer

Do you have validation set up for 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. Try before_validation :autofill_country_code instead.